<?php

namespace app\api\controller;

use app\api\logic\SendMobile;
use think\Db;
use app\api\logic\Task;
use app\common\lib\SendIntegralNew;
use app\company\logic\Message;
use think\Cache;
use app\company\controller\File;

class User extends Base
{
    //登录
    public function login()
    {
        $mobile = I('mobile', '');//手机号码
        $password = I('password', '');//密码
        $account_code = I('account_code', '');//企业代码
        if (empty($mobile)) {
            return return_json(1, '手机号码不能为空');
        }
        if (empty($password)) {
            return return_json(1, '密码不能为空');
        }
        if (empty($account_code)) {
            return return_json(1, '企业代码不能为空');
        }

        //验证企业代码
        $com = M('company')->where('account_code', $account_code)->find();
        if (empty($com)) {
            return return_json(1, '组织代码有误');
        }
        if ($com['status'] == 0) {
            return return_json(1, '该企业已关闭');
        }
        $where['com_id'] = $com['id'];
        $where['mobile'] = $mobile;
        $where['password'] = md5($password);
        $users = M('users')->where($where)->find();
        if (empty($users)) {
            return return_json(1, '手机号或密码或企业代码不正确');
        }
        if($users['status'] == 2){
            return return_json(1,'该用户已冻结');
        }
        if($users['type'] == 2 && !empty($users['role_id'])){
            return return_json(1,'该用户已冻结');
        }
        $data['uid'] = $users['id'];
        $data['name'] = $users['name'];
        $data['status'] = $users['status'];
        $data['mobile'] = $users['mobile'];
        $data['total_integral'] = $users['integral_b'] + $users['base_integral'] + $users['working_age_integral'];
        $data['avatar'] = getImageUrl($users['avatar']);
        $data['com_name'] = $com['name'];
        //判断是否到期提醒
        $time = time()+30*24*3600;
        $data['warn_status'] = 0;
        $data['warn_msg'] = '';
        if($com['use_time'] < $time){
            $day = ceil(($com['use_time'] - time())/(24*3600));
            if($com['use_time'] <= time()){
                $day = 0;
            }
            $data['warn_msg'] = '本企业还有'.$day.'天到期,请尽快续费!';
            $data['warn_status'] = 1;
        }
        return return_json(0, '登录成功', $data);
    }

    //发送验证码
    public function send_code()
    {
        $mobile = I('mobile', '');
        if (empty($mobile)) {
            return return_json(1, '手机不能为空');
        }
        $code = rand('1111', '9999');
        $data = SendMobile::send_mobile($code, $mobile);
        if ($data['status'] == 1) {
            $data_sms = [
                'mobile' => $mobile,
                'code' => $code,
                'status' => 0,
                'create_time' => time(),
            ];
            M('send_sms_log')->insert($data_sms);
            return return_json(0, '发送成功');
        } else {
            return return_json(1, $data['msg']);
        }
    }

    //忘记密码
    public function forget_password()
    {
        $mobile = I('mobile', '');
        $code = I('code', '');
        $password = I('password', '');
        $re_password = I('re_password', '');
        if (empty($mobile)) {
            return return_json(1, '手机号不能为空');
        }
        if (empty($code)) {
            return return_json(1, '验证码不能为空');
        }
        if (empty($password)) {
            return return_json(1, '密码不能为空');
        }
        if (empty($re_password)) {
            return return_json(1, '重复不能为空');
        }
        $result = $this->code_check($mobile, $code);//验证验证码
        if ($result[0] == 1) {
            return return_json(1, $result[1]);
        }
        $users = M('users')->where('mobile', $mobile)->find();
        if (empty($users)) {
            return return_json(1, '该用户不存在');
        }
        if ($password != $re_password) {
            return return_json(1, '密码和重复密码不一致');
        }
        //修改密码
        M('users')->where('id', $users['id'])->update(['password' => md5($password)]);
        return return_json(0, '修改成功');
    }
    //用户注销
    public function user_cancel(){
        $uid = $this->user_id;
        $update_data = [
            'account'=>'',
            'name'=>'已注销',
            'status'=>2,
            'type'=>2
        ];
        M('users')->where('id',$uid)->update($update_data);
        return return_json(0, '操作成功');
    }
    //修改密码
    public function update_password()
    {
        $uid = $this->user_id;
        $password_old = I('password_old', '');//原密码
        $password = I('password', '');//新密码
        $re_password = I('re_password', '');//重复密码
        if (empty($password_old)) {
            return return_json(1, '原密码不能为空');
        }
        if (empty($password)) {
            return return_json(1, '新密码不能为空');
        }
        if (empty($re_password)) {
            return return_json(1, '重复密码不能为空');
        }
        if ($password != $re_password) {
            return return_json(1, '新密码和重复密码不同');
        }
        $users = M('users')->where('id', $uid)->find();
        if ($users['password'] != md5($password_old)) {
            return return_json(1, '原密码不正确');
        }
        //修改密码
        M('users')->where('id', $users['id'])->update(['password' => md5($password)]);
        return return_json(0, '修改成功');
    }
    //上传图片
    public function upload_img(){
        $file = new File();
        $request = request();
        $res = $file->store_api($request);
        if($res['err'] == 0){
            $url = getImageUrl($res['data']['saveName']);
            return return_json(0, '成功',['url'=>$url]);
        }else{
            return return_json(1, $res['msg']);
        }
    }
    //修改用户头像
    public function update_avatar(){
        $uid = $this->user_id;
        $avatar = I('avatar', '');
        if(empty($avatar)){
            return return_json(1, '用户头像不能为空');
        }
        M('users')->where('id', $uid)->update(['avatar' => $avatar]);
        return return_json(0, '修改成功');
    }

    //企业注册
    public function com_register()
    {
        $mobile = I('mobile', '');//移动电话
        $com_mobile = I('com_mobile', ''); //公司电话
        $principal = I('principal', '');//负责人
        $code = I('code', '');//验证码
        $name = I('name', '');//公司名称
        if (empty($mobile)) {
            return return_json(1, '手机号不能为空');
        }
        if (empty($com_mobile)) {
            return return_json(1, '公司手机号不能为空');
        }
        if (empty($principal)) {
            return return_json(1, '负责人不能为空');
        }
        if (empty($code)) {
            return return_json(1, '验证码不能为空');
        }
        if (empty($name)) {
            return return_json(1, '企业名称不能为空');
        }
        $result = $this->code_check($mobile, $code);//验证验证码
        if ($result[0] == 1) {
            return return_json(1, $result[1]);
        }
        $where['mobile'] = $mobile;
        $com = M('company_log')->where($where)->find();
        if (!empty($com)) {
            return return_json(1, '不能重复注册');
        }
        $data_com = [
            'name' => $name,//企业名称
            'mobile' => $mobile,
            'com_mobile' => $com_mobile,
            'create_time' => time(),
            'principal' => $principal //负责人
        ];
        $id = M('company_log')->insertGetId($data_com);
        if (empty($id)) {
            return return_json(1, '注册失败');
        }
        return return_json(0, '注册成功');
    }

    //工作台
    public function workbench()
    {
        //轮播图
        $slide = M('slide')->order('sort asc')->field('image')->select();
        if (!empty($slide)) {
            foreach ($slide as $key => $value) {
                $slide[$key]['image'] = getImageUrl($value['image']);
            }
        }
        $uid = $this->user_id;
        //查询用户身份
        $user = M('com_prize_buckle_relation_users')->where(['user_id'=>$uid,'prize_buckle_id'=>['neq',0]])->find();
        if (empty($user)) {
            $status = 1;
        } else {
            $status = 2;
        }
        $data = [
            'slide' => $slide,
            'status' => $status,
        ];
        //判断是否到期提醒
        $time = time()+30*24*3600;
        $data['warn_status'] = 0;
        $data['warn_msg'] = '';
        //商城导航是否显示
        $com_config = M('com_config')->where('com_id',$this->com_id)->field('is_open_shop,is_open_ranking')->find();
        $data['is_open_show'] = $com_config['is_open_shop'];
        $data['is_open_ranking'] = $com_config['is_open_ranking'];

        $use_time = M('company')->where('id',$this->com_id)->column('use_time');
        if($use_time < $time){
            $day = ceil(($use_time - time())/(24*3600));
            if($use_time <= time()){
                $day = 0;
            }
            $data['warn_msg'] = '本企业还有'.$day.'天到期,请尽快续费!';
            $data['warn_status'] = 1;
        }

        return return_json(0, '获取成功', $data);
    }

    //我的积分
    public function my_integral()
    {
        $year = I('year', '');//年份
        $month = I('month', '');//月份
        if (empty($year)) {
            return return_json(1, '年份不能为空');
        }
        if (empty($month)) {
            return return_json(1, '月份不能为空');
        }
        if(strlen($month) == 1){
            $month = '0'.$month;
        }
        $uid = $this->user_id;
        $users = M('users')->where('id', $uid)->find();
        $users['integral_b'] = SendIntegralNew::statistic_integral(strtotime('2019-01-01'),time(),$uid,0);
        $where['user_id'] = $uid;
        $where['year'] = $year;
        $where['month'] = $month;
        $where['com_id'] = $this->com_id;
        $list = M('com_integral_log')
            ->where($where)
            ->field('COALESCE(sum(if(type = 0,integral_a,0)),0) as total_a,COALESCE(sum(integral_b),0) as total,COALESCE(sum(IF(integral_b > 0,integral_b,0)),0) total_add,COALESCE(sum(IF(integral_b < 0,integral_b,0)),0) total_del,
            COALESCE(sum(IF(type = 0,integral_b,0)),0) total_day,COALESCE(sum(IF(type = 1,integral_b,0)),0) total_fixation,COALESCE(sum(IF(type = 2,integral_b,0)),0) total_price,
            COALESCE(sum(IF(type = 3,integral_b,0)),0) total_other')
            ->find();
        $start_time = strtotime($year.$month.'01');
        $end_time = strtotime('+1 month',$start_time)-1;
        $where_1['a.prize_buckle_time'] = ['between', [$start_time, $end_time]];//奖扣时间
        $where_1['a.status'] = 2; //审核通过
        $where_1['c.is_cancellation'] = 0; //未作废
        $where_1['c.user_id'] = $this->user_id; //用户自己的积分
        $res = M('com_integral_prize_buckle a')
            ->join('com_integral_prize_buckle_relation_event b','b.prize_buckle_id=a.id','right')
            ->join('com_integral_event_relation_users c','c.event_id=b.id','right')
            ->where($where_1)
            ->field('COALESCE(sum(IF(c.integral_b>0,IF(c.piece_rate=0,c.integral_b,c.integral_b*c.piece_rate),0)),0) integral_b_add,
            COALESCE(sum(IF(c.integral_b<0,IF(c.piece_rate=0,c.integral_b,c.integral_b*c.piece_rate),0)),0) integral_b_del,
            COALESCE(sum(IF(c.piece_rate=0,c.integral_a,c.integral_a*c.piece_rate)),0) total_a,
            COALESCE(count(c.id),0) people_sum')
            ->find();
        $uid = $this->user_id;
        $where = [];
        $where['user_id'] = $uid;
        $where['year'] = $year;
        $where['month'] = $month;
        $where['type'] = 2;//奖扣任务
        //奖-扣分
        $prize_integral = M('com_integral_log')->where($where)->where('prize_buckle_type = 1')->value('integral_b');
        //扣-扣分
        $buckle_integral = M('com_integral_log')->where($where)->where('prize_buckle_type = 2')->value('integral_b');
        //人次-扣分
        $people_integral = M('com_integral_log')->where($where)->where('prize_buckle_type = 3')->value('integral_b');
        //比例-扣分
        $rate_integral = M('com_integral_log')->where($where)->where('prize_buckle_type = 4')->value('integral_b');
        $list['total_add'] = $res['integral_b_add'];
        $list['total_del'] = $res['integral_b_del'];
        $list['total_a'] = $res['total_a'];
        $list['total_day'] = $res['integral_b_add']+$res['integral_b_del'];
        $list['total'] = $list['total_day'];
        $list['total_price'] = $prize_integral+$buckle_integral+$people_integral+$rate_integral;
        $list['total_all'] = $users['integral_b'] + $users['base_integral'] + $users['working_age_integral'];
        return return_json(0, '获取成功', $list);
    }

    //日常奖扣
    public function day_price_buckle()
    {
        $year = I('year', '');//年份
        $month = I('month', '');//月份
        $page = I('page', 1);
        if (empty($year)) {
            return return_json(1, '年份不能为空');
        }
        if (empty($month)) {
            return return_json(1, '月份不能为空');
        }
        $time_s = strtotime($year . '/' . $month . '/01');
        $time_e = strtotime('+1 month',$time_s) - 1;
        $uid = $this->user_id;
        $where['a.prize_buckle_time'] = ['between', [$time_s, $time_e]];//终审时间
        $where['c.user_id'] = $uid;
        $where['a.status'] = 2;//审核通过
        $where['c.is_cancellation'] = 0;//未作废
        $where['a.com_id'] = $this->com_id;
        $res = M('com_integral_prize_buckle a')
            ->join('com_integral_prize_buckle_relation_event b', 'b.prize_buckle_id=a.id', 'right')
            ->join('com_integral_event_relation_users c', 'c.event_id=b.id', 'right')
            ->join('com_event d', 'd.id = b.event_id', 'left')
            ->join('com_event_cate e', 'e.id = d.cate_id', 'left')
            ->join('com_event_cate f', 'f.id = e.pid', 'left')
            ->join('com_event_cate g', 'g.id = f.pid', 'left')
            ->order('a.prize_buckle_time desc,a.id desc,b.id desc')
            ->where($where)
            ->field('a.prize_buckle_time,c.id,e.name,f.name p_name,g.name g_name,IFNULL(if(c.piece_rate>0,c.integral_b*c.piece_rate,c.integral_b),0) integral_b,d.name event_name')
            ->paginate(11, false, page_param());
        $count = M('com_integral_prize_buckle a')
            ->join('com_integral_prize_buckle_relation_event b', 'b.prize_buckle_id=a.id', 'right')
            ->join('com_integral_event_relation_users c', 'c.event_id=b.id', 'right')
            ->where($where)
            ->count();
        $count_page = ceil($count / 11);
        $list = $res->items();
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                $list[$key]['time'] = date('m-d', $value['prize_buckle_time']);
                $list[$key]['week'] = $this->time_change_week($value['prize_buckle_time']);
                if (empty($value['p_name'])) {
                    $list[$key]['cate_name'] = $value['name'];
                } else {
                    if (empty($value['g_name'])) {
                        $list[$key]['cate_name'] = $value['p_name'];
                    } else {
                        $list[$key]['cate_name'] = $value['g_name'];
                    }
                }
                unset($list[$key]['name']);
                unset($list[$key]['prize_buckle_time']);
                unset($list[$key]['p_name']);
                unset($list[$key]['g_name']);
            }
        }
        $data = [
            'list' => $list,
            'page' => (int)$page,
            'count_page' => $count_page,
        ];
        return return_json(0, '获取成功', $data);
    }

    //积分详情
    public function integral_info()
    {
        $uid = $this->user_id;
        $id = I('id', 0);
        if (empty($id)) {
            return return_json(1, '事件id不能为空');
        }
        $where['c.id'] = $id;
//        $where['c.user_id'] = $uid;
        $res = M('com_integral_prize_buckle a')
            ->join('com_integral_prize_buckle_relation_event b', 'b.prize_buckle_id=a.id', 'right')
            ->join('com_integral_event_relation_users c', 'c.event_id=b.id', 'right')
            ->join('com_event d', 'd.id = b.event_id', 'left')
            ->join('users e', 'e.id = a.record_user_id', 'left')
            ->join('users f', 'f.id = a.first_check_user_id', 'left')
            ->join('users g', 'g.id = a.last_check_user_id', 'left')
            ->field('a.create_time,a.status,a.theme,d.name,b.event_desc,
            if(c.piece_rate>0,c.integral_a*c.piece_rate,c.integral_a) integral_a,
            if(c.piece_rate>0,c.integral_b*c.piece_rate,c.integral_b) integral_b,
            e.name record_name
            ,f.name first_name,g.name last_name,a.desc,b.img')
            ->where($where)
            ->find();
        $res['create_time'] = date('Y-m-d', $res['create_time']);
        if (!empty($res['img'])) {
            $res['img'] = explode(',', $res['img']);
        } else {
            $res['img'] = [];
        }
        return return_json(0, '获取成功', $res);


    }

    //固定积分
    public function fixed_integral()
    {
        $year = I('year', '');//年份
        $month = I('month', '');//月份
        if (empty($year)) {
            return return_json(1, '年份不能为空');
        }
        if (empty($month)) {
            return return_json(1, '月份不能为空');
        }
        if(strlen($month) == 1){
            $month = '0'.$month;
        }
        $uid = $this->user_id;
        $where['c.user_id'] = $uid;
        $where['c.year'] = $year;
        $where['c.month'] = $month;
        $res = M('com_fixed_integral a')
            ->join('com_integral_log c', 'c.fixed_id = a.id', 'left')
            ->where($where)
            ->field('a.name,a.integral,c.integral_b,type')
            ->select();
        $where_fixed = [];
        $start_time = strtotime($year.'-'.$month.'-'.'01');
        $end_time = strtotime('+1 month',$start_time)-1;
        $where_fixed['com_id'] = $this->com_id;
        $where_fixed['user_id'] = $this->user_id;
        $where_fixed['status'] = 2;
        $where_fixed['last_check_time'] = ['between',[$start_time,$end_time]];
        $total_del = M('com_leave')->where($where_fixed)->sum('fixed_deduct');
        $add_data = [
            'name'=>'当月请假扣固定总积分',
            'integral'=>$total_del,
            'integral_b'=>$total_del,
            'type'=>2,
        ];
        array_push($res,$add_data);
        return return_json(0, '获取成功', $res);
    }

    //奖扣任务
    public function prize_buckle()
    {
        $year = I('year', '');//年份
        $month = I('month', '');//月份
        if (empty($year)) {
            return return_json(1, '年份不能为空');
        }
        if (empty($month)) {
            return return_json(1, '月份不能为空');
        }
        if(strlen($month) == 1){
            $month = '0'.$month;
        }
        $uid = $this->user_id;
        $where['user_id'] = $uid;
        $where['year'] = $year;
        $where['month'] = $month;
        $where['type'] = 2;//奖扣任务
        //奖-扣分
        $prize_integral = M('com_integral_log')->where($where)->where('prize_buckle_type = 1')->value('integral_b');
        //扣-扣分
        $buckle_integral = M('com_integral_log')->where($where)->where('prize_buckle_type = 2')->value('integral_b');
        //人次-扣分
        $people_integral = M('com_integral_log')->where($where)->where('prize_buckle_type = 3')->value('integral_b');
        //比例-扣分
        $rate_integral = M('com_integral_log')->where($where)->where('prize_buckle_type = 4')->value('integral_b');
        $data = [
            'prize_integral' => $prize_integral ? $prize_integral : 0,
            'buckle_integral' => $buckle_integral ? $buckle_integral : 0,
            'people_integral' => $people_integral ? $people_integral : 0,
            'rate_integral' => $rate_integral ? $rate_integral : 0,
        ];
        return return_json(0, '获取成功', $data);

    }

    //其他积分
    public function other_integral()
    {
        $year = I('year', '');//年份
        $month = I('month', '');//月份
        if (empty($year)) {
            return return_json(1, '年份不能为空');
        }
        if (empty($month)) {
            return return_json(1, '月份不能为空');
        }
        if(strlen($month) == 1){
            $month = '0'.$month;
        }
        $uid = $this->user_id;
        $where['user_id'] = $uid;
        $where['year'] = $year;
        $where['month'] = $month;
        $where['type'] = 3;//其他类型  考勤
        //事假
        $thing_integral = M('com_integral_log')->where($where)->where('leave_type = 1')->value('integral_b');
        //病假
        $disease_integral = M('com_integral_log')->where($where)->where('leave_type = 2')->value('integral_b');
        //其他
        $absenteeism_integral = M('com_integral_log')->where($where)->where('leave_type = 3')->value('integral_b');
        //全勤
        $all_integral = M('com_integral_log')->where($where)->where('leave_type = 4')->value('integral_b');
        $data = [
            'thing_integral' => $thing_integral ? $thing_integral : 0,
            'disease_integral' => $disease_integral ? $disease_integral : 0,
            'absenteeism_integral' => $absenteeism_integral ? $absenteeism_integral : 0,
            'all_integral' => $all_integral ? $all_integral : 0,
        ];
        return return_json(0, '获取成功', $data);
    }

    //我的累积积分
    public function accumulate_integral()
    {
        $uid = $this->user_id;
        $where['user_id'] = $uid;
        $where['type'] = 0;
        //基础分
        $users = M('users')->where('id', $uid)->find();
        $users['integral_b'] = SendIntegralNew::statistic_integral(strtotime('2019-01-01'),time(),$uid,0);
        $cache_name = md5($uid);
        //获取缓存
        if(Cache::get($cache_name)){
            $res = unserialize(Cache::get($cache_name));
        }else {
            $year_month_min = strtotime(date('Y-01-01',time()));
            $where['a.year_month'] = ['egt',$year_month_min];
            $res = M('com_integral_log a')
                ->where($where)
                ->field('a.year_month')
                ->group('year_month')
                ->order('year_month desc')
                ->select();
//            var_dump($res);die;
            foreach ($res as $key => $value) {
                $start_time = $value['year_month'];
                $end_time = strtotime('+1 month', $start_time) - 1;
                $where_1 = [];
                $where_1['a.prize_buckle_time'] = ['between', [$start_time, $end_time]];//奖扣时间
                $where_1['a.status'] = 2; //审核通过
                $where_1['c.is_cancellation'] = 0; //未作废
                $where_1['c.user_id'] = $this->user_id; //用户自己的积分
                $res_a = M('com_integral_prize_buckle a')
                    ->join('com_integral_prize_buckle_relation_event b', 'b.prize_buckle_id=a.id', 'right')
                    ->join('com_integral_event_relation_users c', 'c.event_id=b.id', 'right')
                    ->where($where_1)
                    ->field('COALESCE(sum(IF(c.integral_b>0,IF(c.piece_rate=0,c.integral_b,c.integral_b*c.piece_rate),0)),0) integral_b_add,
            COALESCE(sum(IF(c.integral_b<0,IF(c.piece_rate=0,c.integral_b,c.integral_b*c.piece_rate),0)),0) integral_b_del,
            COALESCE(sum(IF(c.piece_rate=0,c.integral_b,c.integral_b*c.piece_rate)),0) total_a')
                    ->find();
                $res[$key]['prize'] = $res_a['integral_b_add'];
                $res[$key]['buckle'] = $res_a['integral_b_del'];
                $res[$key]['total'] = $res_a['total_a'];
            }


            if (!empty($res)) {
                foreach ($res as $key => $value) {
                    $res[$key]['year_month'] = date('Y-m', $value['year_month']);
                }
            }
            //设置缓存
            Cache::set($cache_name,serialize($res),300);
        }
        $data = [
            'total' => $users['integral_b'] + $users['base_integral'] + $users['working_age_integral'],
            'base_integral' => $users['base_integral'],
            'working_age_integral' => $users['working_age_integral'],
            'list' => $res
        ];
        return return_json(0, '获取成功', $data);
    }

    //积分排名
    public function integral_ranking()
    {
        $uid = $this->user_id;
        $where['user_id'] = $uid;
        //用户信息
        $users = M('users a')
            ->join('com_department b', 'b.id=a.department_id', 'left')
            ->field('a.*,b.name department_name')
            ->where('a.id', $uid)->find();
        $users['integral_b'] = SendIntegralNew::statistic_integral(strtotime('2019-01-01'),time(),$uid,0);
        //本月积分
        $time = strtotime(date('Y-m', time()));
        $month_integral = SendIntegralNew::statistic_integral($time,time(),$uid,0);
        //阶段积分
        $time_stage_s = strtotime(date('Y', time()) . '-01');
        $stage_integral = SendIntegralNew::statistic_integral($time_stage_s,time(),$uid,0);
        //累计积分
        $total_integral = $users['integral_b'] + $users['base_integral'] + $users['working_age_integral'];
        //我的积分排名
        $where_2['d.user_id'] = $uid;
        $res = M('com_statistics_statement a')
            ->join('com_statement_relation_group b', 'b.statement_id = a.id', 'left')
            ->join('com_statistics_group c', 'c.id = b.group_id', 'left')
            ->join('com_statistics_group_relation_users d', 'd.group_id = b.group_id', 'left')
            ->where($where_2)
            ->group('a.id')
            ->field('a.id,a.name')
            ->select();
        $data = [
            'name' => $users['name'],
            'department_name' => $users['department_name'],
            'avatar' => getImageUrl($users['avatar']),
            'month_integral' => $month_integral,
            'stage_integral' => $stage_integral,
            'total_integral' => $total_integral,
            'list' => $res
        ];
        return return_json(0, '获取成功', $data);
    }

    //个人报表排名
    public function statement_ranking()
    {
        $time_start = microtime(true);
        $uid = $this->user_id;
        $id = I('id', 0);
        $type = I('type', 1);//类型 1月度排名  2阶段排名  3累计排名
        $group_id = I('group_id', 0);//分组id
        $start_time = I('start_time', date('Y-m', time()));//开始时间
        $end_time = I('end_time', date('Y-m', time()));//结束时间
        if(!empty($group_id)){
            $where['c.id'] = $group_id;
        }
        if (empty($id)) {
            return return_json(1, '报表id不能为空');
        }
        if($type ==1){
            $s_time_int = strtotime($start_time.'-01');
            $e_time_int = strtotime('+1 month',$s_time_int)-1;
        }elseif($type == 2){
            $start_time = I('start_time', date('Y-m-d', time()));//开始时间
            $end_time = I('end_time', date('Y-m-d', time()));//结束时间
            $s_time_int = strtotime($start_time);
            $e_time_int = strtotime('+1 day',strtotime($end_time))-1;
        }else{
            $s_time_int = strtotime('2019-01-01');
            $e_time_int = time();
        }

        $start_time = strtotime($start_time);

        $end_time = strtotime($end_time);
        $cache_name = md5($uid.$id.$type.$group_id.$start_time.$end_time);
        //获取缓存
        if(Cache::get($cache_name)){
            return return_json(0, '获取成功', unserialize(Cache::get($cache_name)));
        }
        $where['a.id'] = $id;
        $where['f.is_sort'] = 1;
        $where['d.is_participation'] = 0;
//        $where['e.type'] = 0;
        $info = M('com_statistics_statement')->where(['id'=>$id, 'com_id'=>$this->com_id])->find();
        if($info['type'] == 0){
            $res = M('com_statistics_statement a')
                ->join('com_statement_relation_group b', 'b.statement_id = a.id', 'right')
                ->join('com_statistics_group c', 'c.id = b.group_id', 'left')
                ->join('com_statistics_group_relation_users d', 'd.group_id = b.group_id', 'right')
                ->join('users f', 'f.id=d.user_id', 'left')
                ->join('com_department g', 'g.id=f.department_id', 'left')
//                ->join('com_integral_log e', 'e.user_id=d.user_id', 'left')
                ->group('d.user_id')
                ->where($where)
                ->field("f.id,f.name,g.name department_name
                ,f.base_integral,f.working_age_integral,f.integral_b,a.is_join")
//                ,COALESCE(sum(IF(e.year_month = {$start_time},e.integral_b,0)),0) type1_integral
//                ,COALESCE(sum(IF(e.year_month >= {$start_time} and e.year_month <= {$end_time},e.integral_b,0)),0) type2_integral
                ->select();
            $list = [];
            if (!empty($res)) {
                foreach ($res as $key => $value) {
//                    $total_integral = 0;
                    if ($type == 1 || $type == 2) {
                        if($value['is_join'] == 0){
                            $total_integral=SendIntegralNew::statistic_integral($s_time_int,$e_time_int,$value['id'],1);
                        }else{
                            $total_integral=SendIntegralNew::statistic_integral($s_time_int,$e_time_int,$value['id'],0);
                        }
                    } elseif ($type == 3) {
                        $total_integral = SendIntegralNew::statistic_integral(strtotime('2019-01-01'),time(),$value['id'],1);;
                    }
                    $list[] = [
                        'name' => $value['name'],
                        'department' => $value['department_name'],
                        'total_integral' => $total_integral,
                        'type'=>0,
                        'id' => $value['id']
                    ];
                }
            }
        }else{
            //获取报表关联的组
            $group_ids = db('com_statement_relation_group')->where(['statement_id'=>$id, 'com_id'=>$this->com_id])->column('group_id');
            $groupNames = db('com_statistics_group')->where('id', 'in', $group_ids)->column('id,name');
            //获取组的成员
            $userInfos = db('com_statistics_group_relation_users a')
                ->join('users b', 'a.user_id = b.id', 'left')
                ->join('com_department c', 'c.id = b.department_id', 'left')
                ->where(['a.group_id'=>['in', $group_ids], 'a.com_id'=>$this->com_id])
                ->where('b.is_sort', 1)         //是否参与排名  0否  1是',
                ->where('a.is_participation', 0)         //是否参与排名  0是  1否',
                ->group('b.id')
                ->field('b.*,b.integral_b integral_aa, c.name as d_name, a.group_id as group_id')
                ->select();
            $tmpUserIds = [];
            foreach ($userInfos as $key=>$value){
                $tmpUserIds[] = $value['id'];
            }
            //查询分组数据
            $group_list = M('com_statement_relation_group a')
                ->join('com_statistics_group b','a.group_id=b.id')
                ->where(['a.statement_id'=>$id, 'a.com_id'=>$this->com_id])
                ->field('a.group_id,b.name')
                ->select();
            foreach ($group_list as $key=>$value){
                $ids = M('users a')
                    ->join('com_statistics_group_relation_users b','b.user_id=a.id')
                    ->where(['a.com_id'=>$this->com_id,'b.group_id'=>$value['group_id'],'a.is_sort'=>1,'b.is_participation'=>0])->column('a.id');
                $count = count($ids);
                $where['user_id'] = ['in',$ids];
                $sum = 0;
                foreach ($ids as $key1=>$value1){
                    //是否加入基础分和工龄分
//                    if($type == 3){
//                        $sum += SendIntegralNew::statistic_integral($s_time_int,$e_time_int,$value1,1);
//                    }else{
                        if($info['is_join'] == 0){
                            $sum += SendIntegralNew::statistic_integral($s_time_int,$e_time_int,$value1,1);
                        }else{
                            $sum += SendIntegralNew::statistic_integral($s_time_int,$e_time_int,$value1,0);
                        }
//                    }

                }
//                var_dump($sum);die;
//                $sum = M('com_integral_log')->where($where)->sum('integral_b');
                //是否加入基础分和工龄分
//                if($info['is_join'] == 0){
//                    $users_integral_total = M('users')->where('id','in',$ids)->field('sum(base_integral) base_integral,sum(working_age_integral) working_age_integral')->find();
//                    $sum = $sum + $users_integral_total['base_integral'] + $users_integral_total['working_age_integral'];
//                }
                if($count == 0 || $sum == 0){
                    $avg = 0;
                }else{
                    $avg = ceil($sum/$count);
                }
                $group_list[$key]['integral_b'] = $avg;
            }
            $list = [];
            foreach ($group_list as $key=>$value){
                $list[] = [
                    'name'=>$value['name'],
                    'total_integral'=>$value['integral_b'],
                    'department'=>$value['name'],
                    'type'=>1,
                    'id'=>$value['group_id'],
                ];
            }
        }
        $group_id = M('com_statistics_group_relation_users')->where('user_id',$uid)->value('group_id');
        //冒泡排序
        $data = $this->data_sort($list, 'total_integral');
        $i = 1;
        $users = [];
        foreach ($data as $key => $value) {
            $data[$key]['sort'] = $i;
            if($info['type'] == 0){
                if ($value['id'] == $uid) {
                    $users['sort'] = $i;
                    $users['total_integral'] = $value['total_integral'];
                }
            }else{
                if ($value['id'] == $group_id) {
                    $users['sort'] = $i;
                    $users['total_integral'] = $value['total_integral'];
                }
            }
            if (isset($data[$key + 1]) && $data[$key + 1]['total_integral'] == $value['total_integral']) {

            } else {
                $i++;
            }

        }
        $time_end = microtime(true);
        $time = $time_end - $time_start;
        $data_retrun = [
            'data' => $data,
            'user' => $users,
            'time'=>$time
        ];
        //设置缓存
        Cache::set($cache_name,serialize($data_retrun),120);
        return return_json(0, '获取成功', $data_retrun);
    }
    //获取报表分组列表
    public function get_statement_group(){
        $uid = $this->user_id;
        $id = I('id', 0);
        if (empty($id)) {
            return return_json(1, '报表id不能为空');
        }
        $list = M('com_statement_relation_group a')
            ->join('com_statistics_group b','b.id=a.group_id')
            ->where('a.statement_id',$id)
            ->field('b.id,b.name')
            ->select();
        $scope_type = M('com_statistics_statement')->where('id',$id)->value('scope_type');
        if($scope_type == 1){
            //只查看所在分组
            foreach ($list as $key=>$value){
                $ids = M('com_statistics_group_relation_users')->where('group_id',$value['id'])->column('user_id');
                if(!in_array($uid,$ids)){
                    unset($list[$key]);
                }
            }
        }
        return return_json(0,'成功',$list);
    }

    //个人报表自定义排名条件
    public function get_condition()
    {
        $uid = $this->user_id;
        $com_id = M('users')->where('id', $uid)->value('com_id');
        //部门用户
        $department = M('com_department')->where('com_id', $com_id)->field('id,name')->select();
        if (!empty($department)) {
            foreach ($department as $key => $value) {
                $users = M('users')->where('department_id', $value['id'])->where('type',1)->field('id,name')->select();
                $department[$key]['user_list'] = $users;
            }
        }
        //事件
        //顶级事件分类
        $top_event = M('com_event_cate')->where('pid', 0)->where('is_del',0)->field('id,name')->select();
        foreach ($top_event as $key => $value) {
            $first_event = M('com_event_cate')->where('pid', $value['id'])->where('com_id', $com_id)->where('is_del',0)->field('id,name')->select();
            if (!empty($first_event)) {
                foreach ($first_event as $k => $v) {
                    $first_event_1 = M('com_event_cate')->where('pid', $v['id'])->where('is_del',0)->field('id,name')->select();
                    $event_1 = M('com_event')->where('cate_id', $v['id'])->where('is_del',0)->where('type',1)->field('id,name')->select();
                    if (!empty($first_event_1)) {
                        foreach ($first_event_1 as $k1 => $v1) {
                            $event_2 = M('com_event')->where('cate_id', $v1['id'])->where('is_del',0)->field('id,name')->select();
                            $first_event_1[$k1]['event'] = $event_2;
                            $first_event_2 = M('com_event_cate')->where('pid', $v1['id'])->where('is_del',0)->field('id,name')->select();
                            if (!empty($first_event_2)) {
                                foreach ($first_event_2 as $k2 => $v2) {
                                    $event_3 = M('com_event')->where('cate_id', $v1['id'])->where('is_del',0)->field('id,name')->select();
                                    $first_event_2[$k2]['event'] = $event_3;
                                }
                            }
                            $first_event1[$k1]['event_list'] = $first_event_2;
                        }
                    }
                    $first_event[$k]['event'] = $event_1;
                    $first_event[$k]['event_list'] = $first_event_1;
                }
            }
            //事件
            $event = M('com_event')->where('cate_id', $value['id'])->where('com_id', $com_id)->where('is_del',0)->where('type',1)->field('id,name')->select();
            $top_event[$key]['event'] = $event;
            $top_event[$key]['event_list'] = $first_event;
        }
        $data = [
            'users' => $department,
            'event' => $top_event,
        ];
        return return_json(0, '获取成功', $data);
    }

    //个人报表自定义排名搜索
    public function custom_search()
    {
        $uid = $this->user_id;
        $com_id = $this->com_id;
        //时间筛选
        $time_type = I('time_type', 1);//时间类型 1月度排名 2季度排名 3年度排名  4总分排名 5阶段排名
        if ($time_type == 1) {
            $time_start = I('time_start', date('Y-m', time()));//时间类型 开始时间
            $s_time_int = strtotime($time_start.'-01');
            $e_time_int = strtotime('+1 month',$s_time_int)-1;
        } elseif ($time_type == 2) {
            $start_time = I('time_start', date('Y-m', time()));//开始时间
            $end_time = I('time_end', date('Y-m', time()));//时间类型 结束时间
            $s_time_int = strtotime($start_time.'-01');
            $e_time_int = strtotime('+1 month',strtotime($end_time.'-01'))-1;
        } elseif ($time_type == 3) {
            $start_time = I('time_start', date('Y', time()));//开始时间
            $s_time_int = strtotime($start_time.'-01-01');
            $e_time_int = strtotime('+1 year',$s_time_int)-1;
        } elseif ($time_type == 4) {
        } elseif ($time_type == 5) {
            $start_time = I('time_start', date('Y-m-d', time()));//开始时间
            $end_time = I('time_end', date('Y-m-d', time()));//结束时间
            $s_time_int = strtotime($start_time);
            $e_time_int = strtotime('+1 day',strtotime($end_time))-1;
        }
        //部门筛选
        $department_type = I('department_type', 1);//部门类型 1所有人员  2指定部门 3指定人员
        $department_list = I('department_ids', ''); //部门id集合
        if (!empty($department_list)) {
            $department_list = json_decode(htmlspecialchars_decode($department_list), true);
            $department_list = json_decode('[' . join(',', $department_list) . ']', true);
            $arr_department = [];
            $list_departmen = M('com_department')->where('com_id',$this->com_id)->field('id,pid')->select();
            foreach ($department_list as $key=>$value){
                $arr = $this->get_department_child($list_departmen,$value,[]);
                $arr_department = array_merge($arr_department,$arr);
            }
            $department_list = $arr_department;
        } else {
            $department_list = [];
        }
        $users = I('user_ids', '');//人员id集合
        if (!empty($users)) {
            $users = json_decode(htmlspecialchars_decode($users), true);
            $users = json_decode('[' . join(',', $users) . ']', true);
        } else {
            $users = [];
        }
        $where = [];
        $where['f.com_id'] = $com_id;
        if ($department_type == 2) {
            $where['g.id'] = ['in', $department_list];
        } elseif ($department_type == 3) {
            $where['f.id'] = ['in', $users];
        }
        //事件筛选
        $event_type = I('event_type', 1);// 1 全部事件 2事件分类和事件id
        $event_cate_ids = I('event_cate_ids', '');//事件分类id
        if (!empty($event_cate_ids)) {
            $event_cate_ids = json_decode(htmlspecialchars_decode($event_cate_ids), true);
            $event_cate_ids = json_decode('[' . join(',', $event_cate_ids) . ']', true);
        } else {
            $event_cate_ids = [];
        }
        $event_ids = I('event_ids', '');//事件id
        if (!empty($event_ids)) {
            $event_ids = json_decode(htmlspecialchars_decode($event_ids), true);
            $event_ids = json_decode('[' . join(',', $event_ids) . ']', true);
        } else {
            $event_ids = [];
        }
        if ($event_type == 2) {
            //查询分类下的所有事件id
            if (!empty($event_cate_ids)) {
                $event_ids__a = $this->get_event_ids($event_cate_ids, $com_id);
                $event_ids = array_merge($event_ids, $event_ids__a);
            }
            $where_1['e.event_id'] = ['in', $event_ids];
        }
        $where['f.is_sort'] = 1;
        $where['f.type'] = 1;
//        $where['f.role_id'] = ['neq',null];
        $res = M('users f')
            ->join('com_department g', 'g.id=f.department_id', 'left')
            ->where($where)
            ->field("f.id,f.name,g.name department_name,f.integral_b,f.base_integral,f.working_age_integral")
            ->select();
        if (!empty($res)) {
            foreach ($res as $key => $value) {
                if($time_type == 4){
                    $total_integral = $value['integral_b']+$value['base_integral']+$value['working_age_integral'];
                }else{
                    $total_integral = SendIntegralNew::statistic_integral($s_time_int,$e_time_int,$value['id'],0,$event_ids);
                }
                $res[$key]['total_integral'] = $total_integral;
            }
            $res = $this->data_sort($res, 'total_integral');
            $i = 1;
            foreach ($res as $key => $value) {
                $res[$key]['sort'] = $i;
                if (isset($res[$key + 1]) && $res[$key + 1]['total_integral'] == $value['total_integral']) {

                } else {
                    $i++;
                }
            }
        }
        return return_json(0, '获取成功', $res);
    }

    //事件分类id获取事件id
    public function get_event_ids($event_cate_ids, $com_id)
    {
        if (!empty($event_cate_ids)) {
            $data = [];
            foreach ($event_cate_ids as $key => $value) {
                $res = M('com_event')->where('cate_id', $value)->where('com_id', $com_id)->where('is_del',0)->column('id');
                if (!empty($res)) {
                    $data = array_merge($data, $res);
                }
                $event_cate = M('com_event_cate')->where('pid', $value)->where('com_id', $com_id)->where('is_del',0)->select();
                if (!empty($event_cate)) {
                    foreach ($event_cate as $k1 => $v1) {
                        $res = M('com_event')->where('cate_id', $v1['id'])->where('is_del',0)->column('id');
                        if (!empty($res)) {
                            $data = array_merge($data, $res);
                        }
                        $event_cate_2 = M('com_event_cate')->where('pid', $v1['id'])->where('is_del',0)->select();
                        if (!empty($event_cate_2)) {
                            foreach ($event_cate_2 as $k2 => $v2) {
                                $res = M('com_event')->where('cate_id', $v2['id'])->where('is_del',0)->column('id');
                                if (!empty($res)) {
                                    $data = array_merge($data, $res);
                                }
                            }
                        }
                    }
                }
            }
            return $data;
        } else {
            return [];
        }
    }

    //积分奖扣
    public function integral_search()
    {
        $time_start = microtime(true);
        $type = I('type', 1);//类型 1我提交的 2 我参与的
        $time = I('time', ''); //年月时间选择
        $start_time = I('start_time', '');//开始时间
        $end_time = I('end_time', ''); //结束时间
        $status = I('status', -1);//-1 全部状态 0待初审 1待终审  2审核通过
        $theme = I('theme', '');//主题
        $event_name = I('event_name', '');
        $uid = $this->user_id;
        $page = I('page', 1);
        if ($type == 1) {
            $where['a.record_user_id'] = $uid;
        } else {
            $where['e.user_id'] = $uid;
        }
        if (!empty($time)) {
            $start = date("Y-m-01", strtotime($time));
            $end = date("Y-m-d", strtotime("$start +1 month -1 day"));
            $where['a.create_time'] = ['between', [strtotime($start), strtotime($end)]];
        }
        if ($status != -1) {
            $where['a.status'] = $status;
        }
        if (!empty($start_time)) {
            $where['a.create_time'] = ['egt', strtotime($start_time)];
        }
        if (!empty($end_time)) {
            $where['a.create_time'] = ['elt', strtotime($end_time)];
        }
        if (!empty($start_time) && !empty($end_time)) {
            $where['a.create_time'] = ['between', [strtotime($start_time), strtotime($end_time)]];
        }
        if (!empty($theme)) {
            $where['a.theme'] = ['like', "%{$theme}%"];
        }
        if (!empty($event_name)) {
            $where['f.name'] = ['like', "%{$event_name}%"];
        }
        if ($type == 1) {
            $res = M('com_integral_prize_buckle a')
                ->join('users b', 'b.id = a.first_check_user_id', 'left')
                ->join('users c', 'c.id = a.last_check_user_id', 'left')
                ->join('com_integral_prize_buckle_relation_event d', 'd.prize_buckle_id=a.id', 'left')
                ->join('com_integral_event_relation_users e', 'e.event_id=d.id', 'left')
                ->where($where)
                ->group('a.id')
                ->order('a.create_time desc')
                ->field('a.id,a.check_status,a.theme,a.create_time,a.people_sum
        ,a.status,b.name first_name, c.name last_name,a.prize_buckle_time
        ,sum(IF(e.piece_rate=0,e.integral_b,e.piece_rate*e.integral_b)) integral_b
        ,sum(IF(e.piece_rate=0,IF(e.integral_b>0,e.integral_b,0),IF(e.integral_b>0,e.piece_rate*e.integral_b,0))) integral_b_add
        ,sum(IF(e.piece_rate=0,IF(e.integral_b<0,e.integral_b,0),IF(e.integral_b<0,e.piece_rate*e.integral_b,0))) integral_b_del
        ,sum(IF(e.piece_rate=0,e.integral_a,e.piece_rate*e.integral_a)) integral_a
        ,sum(IF(e.piece_rate=0,IF(e.integral_a>0,e.integral_a,0),IF(e.integral_a>0,e.piece_rate*e.integral_a,0))) integral_a_add
        ,sum(IF(e.piece_rate=0,IF(e.integral_a<0,e.integral_a,0),IF(e.integral_a<0,e.piece_rate*e.integral_a,0))) integral_a_del
        ')
                ->paginate(11, false, page_param());
            $count = M('com_integral_prize_buckle a')
                ->join('users b', 'b.id = a.first_check_user_id', 'left')
                ->join('users c', 'c.id = a.last_check_user_id', 'left')
                ->join('com_integral_prize_buckle_relation_event d', 'd.prize_buckle_id=a.id', 'left')
                ->join('com_integral_event_relation_users e', 'e.event_id=d.id', 'left')
                ->where($where)
                ->group('a.id')
                ->count();
        } else {
            $res = M('com_integral_prize_buckle a')
                ->join('users b', 'b.id = a.first_check_user_id', 'left')
                ->join('users c', 'c.id = a.last_check_user_id', 'left')
                ->join('com_integral_prize_buckle_relation_event d', 'd.prize_buckle_id=a.id', 'left')
                ->join('com_integral_event_relation_users e', 'e.event_id=d.id', 'left')
                ->join('com_event f', 'f.id=d.event_id', 'left')
                ->join('com_integral_event_relation_users g', 'g.event_id=d.id', 'left')
                ->where($where)
                ->group('d.id')
                ->order('a.create_time desc')
                ->field('a.id,a.check_status,a.theme,a.create_time,a.prize_buckle_time,a.people_sum
        ,a.status,b.name first_name, c.name last_name,f.name event_name
        ,sum(IF(g.piece_rate=0,g.integral_b,g.piece_rate*g.integral_b)) integral_b
        ,sum(IF(g.piece_rate=0,IF(g.integral_b>0,g.integral_b,0),IF(g.integral_b>0,g.piece_rate*g.integral_b,0))) integral_b_add
        ,sum(IF(g.piece_rate=0,IF(g.integral_b<0,g.integral_b,0),IF(g.integral_b<0,g.piece_rate*g.integral_b,0))) integral_b_del
        ,sum(IF(g.piece_rate=0,g.integral_a,g.piece_rate*g.integral_a)) integral_a
        ,sum(IF(g.piece_rate=0,IF(g.integral_a>0,g.integral_a,0),IF(g.integral_a>0,g.piece_rate*g.integral_a,0))) integral_a_add
        ,sum(IF(g.piece_rate=0,IF(g.integral_a<0,g.integral_a,0),IF(g.integral_a<0,g.piece_rate*g.integral_a,0))) integral_a_del
        ')
                ->paginate(11, false, page_param());
            $count = M('com_integral_prize_buckle a')
                ->join('users b', 'b.id = a.first_check_user_id', 'left')
                ->join('users c', 'c.id = a.last_check_user_id', 'left')
                ->join('com_integral_prize_buckle_relation_event d', 'd.prize_buckle_id=a.id', 'left')
                ->join('com_integral_event_relation_users e', 'e.event_id=d.id', 'left')
                ->where($where)
                ->group('d.id')
                ->count();
        }
        $count_page = ceil($count / 11);
        $list = $res->items();
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                $list[$key]['create_time'] = date('Y-m-d', $value['create_time']);
                $list[$key]['prize_buckle_time'] = date('Y-m-d', $value['prize_buckle_time']);
            }
        }
        $time_end = microtime(true);
        $time = $time_end - $time_start;
        $data = [
            'list' => $list,
            'page' => (int)$page,
            'count_page' => $count_page,
            'count' => $count,
            'time'=>$time
        ];
        return return_json(0, '获取成功', $data);

    }

    //积分奖扣详情
    public function integral_detail()
    {
        $id = I('id', 0);
        if (empty($id)) {
            return return_json(0, '事件主题id不能为空');
        }
        //主题
        $res = M('com_integral_prize_buckle a')
            ->join('users b', 'b.id = a.first_check_user_id', 'left')
            ->join('users c', 'c.id = a.last_check_user_id', 'left')
            ->join('users d', 'd.id = a.record_user_id', 'left')
            ->join('users j', 'j.id = a.copy_user_id', 'left')
            ->join('com_integral_prize_buckle_relation_event e', 'e.prize_buckle_id=a.id', 'left')
            ->join('com_integral_event_relation_users g', 'g.event_id=e.id', 'left')
            ->join('com_prize_buckle_relation_users h', 'h.user_id=a.last_check_user_id', 'left')
            ->join('com_prize_buckle i', 'i.id=h.prize_buckle_id', 'left')
            ->field('a.check_status,a.theme,a.desc,a.prize_buckle_time,a.people_sum,a.copy_user_id,j.name copy_name
            ,a.first_check_time,a.last_check_time,a.create_time,a.status,a.first_check_opinion,a.reject_type,a.check_status
            ,a.last_check_opinion,b.name first_name, c.name last_name, d.name record_name,a.first_check_user_id,a.last_check_user_id,a.record_user_id
            ,sum(IF(g.piece_rate=0,g.integral_b,g.piece_rate*g.integral_b)) integral_b
            ,sum(IF(g.piece_rate=0,IF(g.integral_b>0,g.integral_b,0),IF(g.integral_b>0,g.piece_rate*g.integral_b,0))) integral_b_add
            ,sum(IF(g.piece_rate=0,IF(g.integral_b<0,g.integral_b,0),IF(g.integral_b<0,g.piece_rate*g.integral_b,0))) integral_b_del
            ,sum(IF(g.piece_rate=0,g.integral_a,g.piece_rate*g.integral_a)) integral_a
            ,sum(IF(g.piece_rate=0,IF(g.integral_a>0,g.integral_a,0),IF(g.integral_a>0,g.piece_rate*g.integral_a,0))) integral_a_add
            ,sum(IF(g.piece_rate=0,IF(g.integral_a<0,g.integral_a,0),IF(g.integral_a<0,g.piece_rate*g.integral_a,0))) integral_a_del
            ,i.integral_a last_check_integral_a
            ,i.integral_b last_check_integral_b
            ')
            ->where('a.id', $id)->find();
        if (!empty($res['prize_buckle_time'])) {
            $res['prize_buckle_time'] = date('Y-m-d', $res['prize_buckle_time']);
        }
        if (!empty($res['first_check_time'])) {
            $res['first_check_time'] = date('Y-m-d', $res['first_check_time']);
        }
        if (!empty($res['last_check_time'])) {
            $res['last_check_time'] = date('Y-m-d', $res['last_check_time']);
        }
        if (!empty($res['create_time'])) {
            $res['create_time'] = date('Y-m-d', $res['create_time']);
        }
        //事件
        $res_c = M('com_integral_prize_buckle_relation_event a')
            ->join('com_event b', 'b.id = a.event_id', 'left')
            ->join('com_event_cate c', 'c.id = b.cate_id', 'left')
            ->join('com_event_cate d', 'd.id = c.pid', 'left')
            ->where('a.prize_buckle_id', $id)
            ->field('a.id,b.id event_id,a.event_desc,b.name,c.name cate_name,d.name p_cate_name
            ,b.is_piece,b.is_check,b.is_lottery_ticket,a.img,b.integral_a_start,b.integral_a_end,b.integral_b_start,b.integral_b_end,b.desc,b.type')
            ->select();
        //参与人
        if (!empty($res_c)) {
            foreach ($res_c as $key => $value) {
                $users = M('com_integral_event_relation_users a')
                    ->join('users b', 'b.id = a.user_id')
                    ->where('a.event_id', $value['id'])
                    ->field('b.name,a.integral_a,a.integral_b,a.piece_rate,a.user_id,a.is_lottery_ticket')
                    ->select();
                $is_over = 0;
                foreach ($users as $k1=>$v1){
                    if($v1['integral_a'] < $value['integral_a_start'] || $v1['integral_a'] > $value['integral_a_end']){
                        $is_over = 1;
                    }
                    if($v1['integral_b'] < $value['integral_b_start'] || $v1['integral_b'] > $value['integral_b_end']){
                        $is_over = 1;
                    }
                }
                $res_c[$key]['users'] = $users;
                $res_c[$key]['is_over'] = $is_over;

                if (!empty($value['img'])) {
                    $res_c[$key]['img'] = explode(',', $value['img']);
                } else {
                    $res_c[$key]['img'] = [];
                }
            }
        }
        $res['event'] = $res_c;
        return return_json(0, '获取成功', $res);
    }

    //积分奖扣添加-获取事件列表,参与人列表,审核人列表
    public function get_integral_parameter()
    {
        $type = I('type', 1);
        //事件
        $uid = $this->user_id;
        $com_id = $this->com_id;
        //审核权限的用户
        $where_2['a.com_id'] = $com_id;
        //过滤默认空权限
        $where_2['a.prize_buckle_id'] = ['neq',0];
        //删除管理员
        $where_2['b.role_id'] = ['neq',''];
        $where_2['b.type'] = 1;
        $list_user = M('com_prize_buckle_relation_users a')
            ->join('users b', 'b.id = a.user_id', 'left')
            ->join('com_department c', 'c.id=b.department_id', 'left')
            ->join('com_prize_buckle d', 'd.id=a.prize_buckle_id', 'left')
            ->field('b.id,b.name,c.name department_name,d.integral_a,d.integral_b')
            ->where($where_2)
            ->select();
        //默认审核人
        $department = M('com_department a')
            ->join('users b','b.department_id=a.id','left')
            ->join('users c','c.id=a.first_check_user_id','left')
            ->join('users d','d.id=a.last_check_user_id','left')
            ->join('com_prize_buckle_relation_users e','e.user_id=d.id','left')
            ->join('com_prize_buckle f','f.id=e.prize_buckle_id','left')
            ->where('b.id',$uid)
            ->where('c.type',1)
            ->where('d.type',1)
            ->field('a.first_check_user_id,a.last_check_user_id,c.name first_name,d.name last_name,f.integral_a,f.integral_b')
            ->find();
        if(empty($department)){
            $department = [
                "first_check_user_id"=>0,
                "last_check_user_id"=>0,
                "first_name"=> "",
                "last_name"=> "",
                "integral_a"=>0,
                "integral_b"=> 0
            ];
        }
        //查询用户部门
        $list = db('com_department')->where(['com_id' => $this->com_id])->field('id,name,pid')->select();
        //删除管理员
        $where_users['a.role_id'] = ['neq',''];
        $where_users['a.com_id'] = $com_id;
        $where_users['a.type'] = 1;
        $users = M('users a')
            ->join('com_department b', 'b.id=a.department_id', 'left')
            ->field('a.id,a.name,b.name department_name,b.id department_id')
            ->where($where_users)
            ->select();
        $users = $this->get_tree_data($list, 0, $users, 'department_id');

        if ($type == 1) {
            //事件
            $where_1['a.com_id'] = $com_id;
            $where_1['a.type'] = 1;//正式库
            $where_1['a.is_del'] = 0;//未删除
            $event = M('com_event a')
                ->join('com_event_cate b', 'b.id=a.cate_id', 'left')
                ->join('com_event_cate c', 'c.id=b.pid', 'left')
//                ->join('users d', 'd.id=a.first_check_user_id', 'left')
//                ->join('users e', 'e.id=a.last_check_user_id', 'left')
                ->field('a.id,a.name,a.is_lottery_ticket,a.is_piece,a.is_check
            ,a.first_check_user_id,a.last_check_user_id,b.name cate_name
            ,c.name p_cate_name
            ,a.integral_a_start,a.integral_b_start,a.integral_a_end,a.integral_b_end,a.desc,b.id cate_id')
                ->where($where_1)->select();
            $users_a = M('users a')
                ->join('com_department b','b.id=a.department_id','left')
                ->join('com_prize_buckle_relation_users e','e.user_id=a.id','left')
                ->join('com_prize_buckle f','f.id=e.prize_buckle_id','left')
                ->where('a.com_id',$com_id)->column('a.id,a.name,b.name department_name,f.integral_a,f.integral_b','a.id');
            foreach ($event as $key=>$value){
                if($value['is_check'] == 1){
                    $first_check_user_ids = explode(',',$value['first_check_user_id']);
                    $first_check_list = [];
                    foreach ($first_check_user_ids as $v1){
                        $first_check_list[] =[
                            'id'=>$v1,
                            'name'=>$users_a[$v1]['name']??'',
                            'department_name'=>$users_a[$v1]['department_name']??'',
                        ];
                    }
                    $last_check_user_ids = explode(',',$value['last_check_user_id']);
                    $last_check_list = [];
                    foreach ($last_check_user_ids as $v2){
                        $last_check_list[] =[
                            'id'=>$v2,
                            'name'=>$users_a[$v2]['name']??'',
                            'department_name'=>$users_a[$v2]['department_name']??'',
                            'integral_a'=>$users_a[$v2]['integral_a']??0,
                            'integral_b'=>$users_a[$v2]['integral_b']??0,
                        ];
                    }
                    $event[$key]['first_check_list'] = $first_check_list;
                    $event[$key]['last_check_list'] = $last_check_list;

                }
            }
            //事件分类
            $event_cate = M('com_event_cate a')->where("com_id = {$this->com_id} or pid = 0")->where('is_del',0)->field('id,name,pid')->select();
            $event = $this->get_tree_data($event_cate, 0, $event, 'cate_id');
            $data = [
                'event' => $event,
                'participant' => $users,
                'check_users' => $list_user,
                'default_check_users'=>$department,
            ];
        } else {
            $data = [
                'participant' => $users,
                'check_users' => $list_user,
                'default_check_users'=>$department,
            ];
        }
        return return_json(0, '获取成功', $data);
    }

    //添加积分奖扣
    public function add_theme()
    {
        $params = input();
        if (empty($params['theme'])) {
            return return_json(1, '主题不能为空');
        }
        if (empty($params['first_check_user_id'])) {
            return return_json(1, '初审人不能为空');
        }
        if (empty($params['prize_buckle_time'])) {
            return return_json(1, '奖扣时间不能为空');
        }
        if ($params['first_check_user_id'] == $params['last_check_user_id']) {
            return return_json(1, '初审和终审人不能是同一人');
        }
        $uid = $this->user_id;
        $com_id = $this->com_id;
        //添加数据
        DB::startTrans();//开启事务
        try {
            $list = json_decode(stripslashes($params['list']), true);
//           return return_json(1,'ces',$list);
            //A分
            $integral_a_add = 0;
            $integral_a_del = 0;
            //B分
            $integral_b_add = 0;
            $integral_b_del = 0;
            //人次
            $people_sum = 0;

            foreach ($list as $key => $value) {
                //查询是否专审事件
                $is_check = M('com_event')->where('id', $value['event']['id'])->value('is_check');
                if ($is_check != 1) {
                    foreach ($value['users'] as $k => $v) {
                        $integral_a = isset($v['integral_a']) ? $v['integral_a'] : 0;
                        $integral_b = isset($v['integral_b']) ? $v['integral_b'] : 0;
                        $piece_rate = isset($v['piece_rate']) ? $v['piece_rate'] : 1;
                        if ($piece_rate == 0) {
                            $piece_rate = 1;
                        }
                        if ($integral_a > 0) {
                            $integral_a_add += (int)$integral_a * $piece_rate;
                        } else {
                            $integral_a_del += (int)$integral_a * $piece_rate;
                        }
                        if ($integral_b > 0) {
                            $integral_b_add += (int)$integral_b * $piece_rate;
                        } else {
                            $integral_b_del += (int)$integral_b * $piece_rate;
                        }
                        $people_sum += 1;
                    }
                } else {
                    //A分
                    $integral_a_add_check = 0;
                    $integral_a_del_check = 0;
                    //B分
                    $integral_b_add_check = 0;
                    $integral_b_del_check = 0;
                    //人次
                    $people_sum_check = 0;
                    foreach ($value['users'] as $k => $v) {
                        $integral_a = isset($v['integral_a']) ? $v['integral_a'] : 0;
                        $integral_b = isset($v['integral_b']) ? $v['integral_b'] : 0;
                        $piece_rate = isset($v['piece_rate']) ? $v['piece_rate'] : 1;
                        if ($piece_rate == 0) {
                            $piece_rate = 1;
                        }
                        if ($integral_a > 0) {
                            $integral_a_add_check += (int)$integral_a * $piece_rate;
                        } else {
                            $integral_a_del_check += (int)$integral_a * $piece_rate;
                        }
                        if ($integral_b > 0) {
                            $integral_b_add_check += (int)$integral_b * $piece_rate;
                        } else {
                            $integral_b_del_check += (int)$integral_b * $piece_rate;
                        }
                        $people_sum_check += 1;
                    }

                    $data_array_check = [
                        'com_id' => $com_id,
                        'first_check_user_id' => $params['first_check_user_id'],
                        'last_check_user_id' => $params['last_check_user_id'],
                        'record_user_id' => $uid,
                        'copy_user_id' => $params['copy_user_id']??0,
                        'prize_buckle_time' => strtotime($params['prize_buckle_time']),
                        'integral_a_add' => $integral_a_add_check,
                        'integral_a_del' => $integral_a_del_check,
                        'integral_b_add' => $integral_b_add_check,
                        'integral_b_del' => $integral_b_del_check,
                        'theme' => $params['theme'],
                        'create_time' => time(),
                        'people_sum' => $people_sum_check,
                        'desc' => isset($params['desc']) ? $params['desc'] : '',
                    ];
                    //初审人和记录人相同跳过初审
                    if ($params['first_check_user_id'] == $uid) {
                        $data_array_check['status'] = 1;
                        $data_array_check['first_check_time'] = time();
                        $data_array_check['first_check_opinion'] = isset($params['first_check_opinion']) ? $params['first_check_opinion'] : '';
                    }
                    //添加主题数据
                    $theme_id_check = M('com_integral_prize_buckle')->insertGetId($data_array_check);
                    $img = [];
                    if (isset($value['imageList']) && !empty($value['imageList'])) {
//                        var_dump($value['imageList']);die;
//                        $value['imageList'] = json_decode($value['imageList'],true);
                        foreach ($value['imageList'] as $va) {
                            $img[] = $va['url'];
                        }
                    }

                    //添加事件数据
                    $data_array_event = [
                        'com_id' => $com_id,
                        'prize_buckle_id' => $theme_id_check,
                        'event_id' => $value['event']['id'],
                        'event_desc' => isset($value['event']['event_desc']) ? $value['event']['event_desc'] : '',
                        'img' => implode(',', $img),
                        'create_time' => time(),
                    ];
                    $event_id = M('com_integral_prize_buckle_relation_event')->insertGetId($data_array_event);
                    $event_info = M('com_event')->where('id', $value['event']['id'])->find();
                    //添加参与人
                    if (count($value['users']) == 0) {
                        return return_json(1, '参与人不能为空');
                    }
                    $users_check = [];
                    foreach ($value['users'] as $k => $v) {
                        $integral_a = isset($v['integral_a']) ? $v['integral_a'] : 0;
                        $integral_b = isset($v['integral_b']) ? $v['integral_b'] : 0;
                        $piece_rate = isset($v['piece_rate']) ? $v['piece_rate'] : 1;
                        if ($piece_rate == 0) {
                            $piece_rate = 1;
                        }
                        $data_array_3 = [
                            'com_id' => $this->com_id,
                            'event_id' => $event_id,
                            'user_id' => $v['id'],
                            'integral_a' => $integral_a,
                            'integral_b' => $integral_b,
                        ];
                        if ($event_info['is_piece'] == 1) {
                            $data_array_3['piece_rate'] = $piece_rate;
                        }//计件事件
                        if ($event_info['is_lottery_ticket'] == 1) {
                            $data_array_3['is_lottery_ticket'] = 1;
                        }//奖票事件
                        M('com_integral_event_relation_users')->insert($data_array_3);
                        $users_check[] = $v['id'];
                    }
                    if(!empty($users_check)) {
                        if (count($users_check) != count(array_unique($users_check))) {
                            return return_json(1, '参与人不能重复');
                        }
                    }
                }
            }

            if ($people_sum < 1) {
                DB::commit();//提交
                return return_json(0, "成功");
            }

            $data_array_1 = [
                'com_id' => $com_id,
                'first_check_user_id' => $params['first_check_user_id'],
                'last_check_user_id' => $params['last_check_user_id'],
                'record_user_id' => $uid,
                'copy_user_id' => $params['copy_user_id']??0,
                'prize_buckle_time' => strtotime($params['prize_buckle_time']),
                'integral_a_add' => $integral_a_add,
                'integral_a_del' => $integral_a_del,
                'integral_b_add' => $integral_b_add,
                'integral_b_del' => $integral_b_del,
                'theme' => $params['theme'],
                'create_time' => time(),
                'people_sum' => $people_sum,
                'status' => 0,
                'desc' => isset($params['desc']) ? $params['desc'] : '',
            ];
            //初审人和记录人相同跳过初审
            if ($params['first_check_user_id'] == $uid) {
                $data_array_1['status'] = 1;
                $data_array_1['first_check_time'] = time();
                $data_array_1['first_check_opinion'] = isset($params['first_check_opinion']) ? $params['first_check_opinion'] : '';
            }
            if(empty($params['id'])) {
                //添加主题数据
                $theme_id = M('com_integral_prize_buckle')->insertGetId($data_array_1);
                //添加事件数据
                foreach ($list as $key => $value) {
                    $img = [];
                    if (isset($value['imageList']) && !empty($value['imageList'])) {
//                        var_dump($value['imageList']);die;
//                        $value['imageList'] = json_decode($value['imageList'],true);
                        foreach ($value['imageList'] as $va) {
                            $img[] = $va['url'];
                        }
                    }
                    $data_array_2 = [
                        'com_id' => $com_id,
                        'prize_buckle_id' => $theme_id,
                        'event_id' => $value['event']['id'],
                        'event_desc' => isset($value['event']['event_desc']) ? $value['event']['event_desc'] : '',
                        'img' => implode(',', $img),
                        'create_time' => time(),
                    ];
                    $event_id = M('com_integral_prize_buckle_relation_event')->insertGetId($data_array_2);
                    $event_info = M('com_event')->where('id', $value['event']['id'])->find();
                    //添加参与人
                    if (count($value['users']) == 0) {
                        return return_json(1, '参与人不能为空');
                    }
                    $users_check = [];
                    foreach ($value['users'] as $k => $v) {
                        $integral_a = isset($v['integral_a']) ? $v['integral_a'] : 0;
                        $integral_b = isset($v['integral_b']) ? $v['integral_b'] : 0;
                        $piece_rate = isset($v['piece_rate']) ? $v['piece_rate'] : 1;
                        if ($piece_rate == 0) {
                            $piece_rate = 1;
                        }
                        $data_array_3 = [
                            'com_id' => $com_id,
                            'event_id' => $event_id,
                            'user_id' => $v['id'],
                            'integral_a' => $integral_a,
                            'integral_b' => $integral_b,
                        ];
                        if ($event_info['is_piece'] == 1) {
                            $data_array_3['piece_rate'] = $piece_rate;
                        }//计件事件
                        if ($event_info['is_lottery_ticket'] == 1) {
                            $data_array_3['is_lottery_ticket'] = 1;
                        }//奖票事件

                        M('com_integral_event_relation_users')->insert($data_array_3);
                        $users_check[] = $v['id'];
                    }
                    if (count($users_check) != count(array_unique($users_check))) {
                        return return_json(1, '参与人不能重复');
                    }
                }
            }else{
                //修改主题数据
                $theme_id = $params['id'];
                $data_array_1['check_status'] = 0;
                $data_array_1['reject_type'] = 1;
                M('com_integral_prize_buckle')->where('id',$theme_id)->update($data_array_1);
               //删除事件和用户
                $event_ids = M('com_integral_prize_buckle_relation_event')
                    ->where('prize_buckle_id',$theme_id)
                    ->column('id');
                M('com_integral_event_relation_users')->where('event_id','in',$event_ids)->delete();
                M('com_integral_prize_buckle_relation_event')->where('prize_buckle_id',$theme_id)->delete();
                //添加事件数据
                foreach ($list as $key => $value) {
                    $img = [];
                    if (isset($value['imageList']) && !empty($value['imageList'])) {
//                        var_dump($value['imageList']);die;
//                        $value['imageList'] = json_decode($value['imageList'],true);
                        foreach ($value['imageList'] as $va) {
                            $img[] = $va['url'];
                        }
                    }
//                    if(count($img) < 2){
//                        $img
//                    }
                    $data_array_2 = [
                        'com_id' => $com_id,
                        'prize_buckle_id' => $theme_id,
                        'event_id' => $value['event']['id'],
                        'event_desc' => isset($value['event']['event_desc']) ? $value['event']['event_desc'] : '',
                        'img' => implode(',', $img),
                        'create_time' => time(),
                    ];
                    $event_id = M('com_integral_prize_buckle_relation_event')->insertGetId($data_array_2);
                    $event_info = M('com_event')->where('id', $value['event']['id'])->find();
                    //添加参与人
                    if (count($value['users']) == 0) {
                        return return_json(1, '参与人不能为空');
                    }
                    $users_check = [];
                    foreach ($value['users'] as $k => $v) {
                        $integral_a = isset($v['integral_a']) ? $v['integral_a'] : 0;
                        $integral_b = isset($v['integral_b']) ? $v['integral_b'] : 0;
                        $piece_rate = isset($v['piece_rate']) ? $v['piece_rate'] : 1;
                        if ($piece_rate == 0) {
                            $piece_rate = 1;
                        }
                        $data_array_3 = [
                            'com_id' => $com_id,
                            'event_id' => $event_id,
                            'user_id' => $v['id'],
                            'integral_a' => $integral_a,
                            'integral_b' => $integral_b,
                        ];
                        if ($event_info['is_piece'] == 1) {
                            $data_array_3['piece_rate'] = $piece_rate;
                        }//计件事件
                        if ($event_info['is_lottery_ticket'] == 1) {
                            $data_array_3['is_lottery_ticket'] = 1;
                        }//奖票事件
                        M('com_integral_event_relation_users')->insert($data_array_3);
                        $users_check[] = $v['id'];
                    }
                    if (count($users_check) != count(array_unique($users_check))) {
                        return return_json(1, '参与人不能重复');
                    }
                }
            }
            //发送消息
            $data_message = [];
            if(isset($data_array_1['status'])&&$data_array_1['status'] == 1){
                //终审人
                $data_message[] = [
                    'title' => '您有一条积分奖扣待审核(终审)',
                    'user_id' => $params['last_check_user_id'],
                    'cate_type' => 1,//审核消息
                    'type' => 3,//
                    'relation_id' => $theme_id
                ];
            }else{
                //初审人
                $data_message[] = [
                    'title' => '您有一条积分奖扣待审核(初审)',
                    'user_id' => $params['first_check_user_id'],
                    'cate_type' => 1,//审核消息
                    'type' => 3,//
                    'relation_id' => $theme_id
                ];
            }
            if(isset($params['task_id']) && !empty($params['task_id'])){
                //修改任务状态(已提交)
                M('com_task')->where('id',$params['task_id'])->update(['status'=>4]);
            }
            Message::send_message_list($data_message);
            DB::commit();//提交
            return return_json(0, "成功");
        } catch (\Exception $e) {
            DB::rollback();//回滚
            return return_json(1, '事件名称,描述,备注不能包含特殊字符');
        }
    }

    //搜索事件
    public function search_event()
    {
        //事件
        $name = I('event_name', '');
        if (empty($name)) {
            return return_json(1, '事件名称不能为空');
        }
        $com_id = $this->com_id;
        $where['a.com_id'] = $com_id;
        $where['a.type'] = 1;//正式库
        $where['a.is_del'] = 0;
        $where['a.name'] = ['like', "%{$name}%"];
        $event = M('com_event a')
            ->join('com_event_cate b', 'b.id=a.cate_id', 'left')
            ->join('com_event_cate c', 'c.id=b.pid', 'left')
            ->join('users d', 'd.id=a.first_check_user_id', 'left')
            ->join('users e', 'e.id=a.last_check_user_id', 'left')
            ->field('a.id,a.name,a.is_lottery_ticket,a.is_piece,a.is_check
            ,a.first_check_user_id,a.last_check_user_id,b.name cate_name
            ,c.name p_cate_name,d.name first_name,e.name last_name
            ,a.integral_a_start,a.integral_b_start,a.integral_a_end,a.integral_b_end,a.desc')
            ->where($where)->select();
        return return_json(0, '获取成功', $event);
    }

    //添加临时事件
    public function add_temporary_event()
    {
        $com_id = $this->com_id;
        $name = I('event_name', '');
        if (empty($name)) {
            return return_json(1, '名称不能为空');
        }
        $cate_id = I('cate_id', 3);//默认其他分类
        $where['name'] = $name;
        $where['cate_id'] = $cate_id;
        $where['type'] = 2;//临时事件库
        $where['is_del'] = 0;
        $where['com_id'] = $com_id;
        $res = M('com_event')->where($where)->find();
        if (empty($res)) {
            $data = [
                'com_id' => $com_id,
                'cate_id' => $cate_id,
                'type' => 2,
                'name' => $name,
                'create_time' => time(),
            ];
            $event_id = M('com_event')->insertGetId($data);
            if (empty($event_id)) {
                return return_json(1, '添加失败');
            }
            $event = M('com_event')->where('id', $event_id)->find();
            return return_json(0, '添加成功', $event);
        } else {
            return return_json(0, '添加成功', $res);
        }
    }

    //用户搜索
    public function user_search()
    {
        $name = I('name', '');
        if (empty($name)) {
            return return_json(1, '用户名称不能为空');
        }
        $where['a.name'] = ['like', "%{$name}%"];
        $where['a.com_id'] = $this->com_id;
        $where['a.type'] = 1;
        $res = M('users a')
            ->join('com_department b', 'b.id=a.department_id', 'left')
            ->field('a.id,a.name,a.job_number,b.name department_name')
            ->where($where)
            ->select();
        return return_json(0, '获取成功', $res);
    }

    //组成无限级数的分类和该分类的数据
    public function get_tree_data($arr = [], $id = 0, $arr_1 = [], $item)
    {
        $list = [];
        foreach ($arr as $k => $v) {
            if ($v["pid"] == $id) {
                unset($arr[$k]);
                $v["list"] = $this->get_tree_data($arr, $v["id"], $arr_1, $item);
                $data = [];
                foreach ($arr_1 as $key => $value) {
                    if ($value[$item] == $v['id']) {
                        $data[] = $value;
                    }
                }
                $v['data'] = $data;
                $list[] = $v;
            }
        }
        return $list;
    }

    //我的审核搜索
    public function my_check_pending()
    {
        $time_start = microtime(true);
        $type = I('type', 1);//类型 1待我审核的 2 我已经审核的  3抄送给我的
        $type_cate = I('type_cate', 1);//类型分类 1日常奖扣 2 任务 3公告 4请假
        $time = I('time', ''); //年月时间选择
        $start_time = I('start_time', '');//开始时间
        $end_time = I('end_time', ''); //结束时间
        $status = I('status', -1);//-1 全部状态 0待初审 1待终审  2审核通过
        $theme = I('theme', '');//主题
        $task_name = I('task_name', '');//任务名称
        $notice_name = I('notice_name', '');//公告名称
        $leave_name = I('leave_name', '');//请假名称
        $uid = $this->user_id;
        $page = I('page', 1);
        if ($type_cate == 1) { //日常奖扣
            $where_1_a = '';
            $where_1 = [];
            if ($type == 1) { //待我审核的
                $where_1_a = "(a.status = 0 and a.first_check_user_id = {$uid}) or (a.status = 1 and a.last_check_user_id = {$uid})";
            } elseif ($type == 2) { //我已经审核的
                $where_1_a = "(a.status = 1 and a.first_check_user_id = {$uid}) or (a.status = 2 and (a.last_check_user_id = {$uid} or a.first_check_user_id = {$uid}))";
            } elseif ($type == 3) {//抄送给我的
                $where_1['a.copy_user_id'] = $uid;
            }
            if (!empty($time)) {
                $start = date("Y-m-01", strtotime($time));
                $end = date("Y-m-d", strtotime("$start +1 month -1 day"));
                $where_1['a.create_time'] = ['between', [strtotime($start), strtotime($end)]];
            }
            if ($status != -1) {
                $where_1['a.status'] = $status;
            }
            if (!empty($start_time)) {
                $where_1['a.create_time'] = ['egt', strtotime($start_time)];
            }
            if (!empty($end_time)) {
                $where_1['a.create_time'] = ['elt', strtotime($end_time)];
            }
            if (!empty($start_time) && !empty($end_time)) {
                $where_1['a.create_time'] = ['between', [strtotime($start_time), strtotime($end_time)]];
            }
            if (!empty($theme)) {
                $where_1['a.theme'] = ['like', "%{$theme}%"];
            }
            $res = M('com_integral_prize_buckle a')
                ->join('users b', 'b.id = a.first_check_user_id', 'left')
                ->join('users c', 'c.id = a.last_check_user_id', 'left')
                ->join('users d', 'd.id = a.record_user_id', 'left')
                ->join('com_integral_prize_buckle_relation_event f', 'f.prize_buckle_id=a.id', 'left')
                ->join('com_integral_event_relation_users e', 'e.event_id=f.id', 'left')
                ->where($where_1)
                ->where($where_1_a)
                ->group('a.id')
                ->order('a.create_time desc')
                ->field('a.id,a.theme,a.create_time,a.people_sum
        ,a.status,b.name first_name, c.name last_name,d.name record_name
        ,sum(IF(e.piece_rate=0,e.integral_b,e.piece_rate*e.integral_b)) integral_b
        ,sum(IF(e.piece_rate=0,IF(e.integral_b>0,e.integral_b,0),IF(e.integral_b>0,e.piece_rate*e.integral_b,0))) integral_b_add
        ,sum(IF(e.piece_rate=0,IF(e.integral_b<0,e.integral_b,0),IF(e.integral_b<0,e.piece_rate*e.integral_b,0))) integral_b_del
        ,sum(IF(e.piece_rate=0,e.integral_a,e.piece_rate*e.integral_a)) integral_a
        ,sum(IF(e.piece_rate=0,IF(e.integral_a>0,e.integral_a,0),IF(e.integral_a>0,e.piece_rate*e.integral_a,0))) integral_a_add
        ,sum(IF(e.piece_rate=0,IF(e.integral_a<0,e.integral_a,0),IF(e.integral_a<0,e.piece_rate*e.integral_a,0))) integral_a_del
        ')
                ->paginate(11, false, page_param());
            $count = M('com_integral_prize_buckle a')
                ->where($where_1)
                ->where($where_1_a)
                ->count();
        } elseif ($type_cate == 2) {//任务
            $where_2_a = '';
            $where_2 = [];
            if ($type == 1) { //待我审核的
                $where_2_a = "(a.status = 0 and a.first_check_user_id = {$uid}) or (a.status = 1 and a.last_check_user_id = {$uid})";
            } elseif ($type == 2) { //我已经审核的
                $where_2_a = "(a.status = 1 and a.first_check_user_id = {$uid}) or (a.status in (2,3,4) and (a.last_check_user_id = {$uid} or a.first_check_user_id = {$uid}))";
            }
            if (!empty($time)) {
                $start = date("Y-m-01", strtotime($time));
                $end = date("Y-m-d", strtotime("$start +1 month -1 day"));
                $where_2['a.end_time'] = ['between', [strtotime($start), strtotime($end)]];
            }
            if ($status != -1) {
                if ($status == 2) {
                    $where_2['a.status'] = ['in', [2, 3, 4]];
                } else {
                    $where_2['a.status'] = $status;
                }
            }
            if (!empty($start_time)) {
                $where_2['a.end_time'] = ['egt', strtotime($start_time)];
            }
            if (!empty($end_time)) {
                $where_2['a.end_time'] = ['elt', strtotime($end_time)];
            }
            if (!empty($start_time) && !empty($end_time)) {
                $where_2['a.end_time'] = ['between', [strtotime($start_time), strtotime($end_time)]];
            }
            if (!empty($task_name)) {//任务名称
                $where_2['a.name'] = ['like', "%{$task_name}%"];
            }
            $res = M('com_task a')
                ->join('users b', 'b.id=a.principal_user_id', 'left')
                ->join('users c', 'c.id=a.first_check_user_id', 'left')
                ->join('users d', 'd.id=a.last_check_user_id', 'left')
                ->join('users e', 'e.id=a.record_user_id', 'left')
                ->field('a.id,a.name,a.type,a.apply_integral,a.apply_end_time,a.end_time,a.del_integral,a.status,c.name first_name,b.name principal_name,d.name last_name,e.name record_name,a.del_integral_double,a.double_max,a.del_integral,del_type')
                ->where($where_2)
                ->where($where_2_a)
                ->order('a.create_time desc')
                ->paginate(11, false, page_param());
            $count = M('com_task a')
                ->where($where_2)
                ->where($where_2_a)
                ->count();
        } elseif ($type_cate == 3) { //公告
            $where_3_a = '';
            $where_3 = [];
            if ($type == 1) { //待我审核的
                $where_3_a = "(a.status = 0 and a.first_check_user_id = {$uid}) or (a.status = 1 and a.last_check_user_id = {$uid})";
            } elseif ($type == 2) { //我已经审核的
                $where_3_a = "(a.status = 1 and a.first_check_user_id = {$uid}) or (a.status in (2,3) and (a.last_check_user_id = {$uid} or a.first_check_user_id = {$uid}))";
            }
            if (!empty($time)) {
                $start = date("Y-m-01", strtotime($time));
                $end = date("Y-m-d", strtotime("$start +1 month -1 day"));
                $where_3['a.end_time'] = ['between', [strtotime($start), strtotime($end)]];
            }
            if ($status != -1) {
                if ($status == 2) {
                    $where_3['a.status'] = ['in', [2, 3]];
                } else {
                    $where_3['a.status'] = $status;
                }
            }
            if (!empty($start_time)) {
                $where_3['a.end_time'] = ['egt', strtotime($start_time)];
            }
            if (!empty($end_time)) {
                $where_3['a.end_time'] = ['elt', strtotime($end_time)];
            }
            if (!empty($start_time) && !empty($end_time)) {
                $where_3['a.end_time'] = ['between', [strtotime($start_time), strtotime($end_time)]];
            }
            if (!empty($notice_name)) {//公告名称
                $where_3['a.name'] = ['like', "%{$notice_name}%"];
            }
            $res = M('com_notice a')
                ->join('users b', 'b.id=a.first_check_user_id', 'left')
                ->join('users c', 'c.id=a.last_check_user_id', 'left')
                ->join('users d', 'd.id=a.record_user_id', 'left')
                ->where($where_3)
                ->where($where_3_a)
                ->order('a.create_time desc')
                ->field('a.id,a.name,a.read_integral,a.not_read_integral,a.end_time,a.status,c.name last_name,b.name first_name,d.name record_name')
                ->paginate(11, false, page_param());
            $count = M('com_notice a')
                ->where($where_3)
                ->where($where_3_a)
                ->count();
        } elseif ($type_cate == 4) {//请假
            $where_4_a = '';
            $where_4 = [];
            if ($type == 1) { //待我审核的
                $where_4_a = "(a.status = 0 and a.first_check_user_id = {$uid}) or (a.status = 1 and a.last_check_user_id = {$uid})";
            } elseif ($type == 2) { //我已经审核的
                $where_4_a = "(a.status = 1 and a.first_check_user_id = {$uid}) or (a.status = 2 and (a.last_check_user_id = {$uid} or a.first_check_user_id = {$uid}))";
            }
            if (!empty($time)) {
                $start = date("Y-m-01", strtotime($time));
                $end = date("Y-m-d", strtotime("$start +1 month -1 day"));
                $where_4['a.start_time'] = ['between', [strtotime($start), strtotime($end)]];
            }
            if ($status != -1) {
                $where_4['a.status'] = $status;
            }
            if (!empty($start_time)) {
                $where_4['a.start_time'] = ['egt', strtotime($start_time)];
            }
            if (!empty($end_time)) {
                $where_4['a.start_time'] = ['elt', strtotime($end_time)];
            }
            if (!empty($start_time) && !empty($end_time)) {
                $where_4['a.start_time'] = ['between', [strtotime($start_time), strtotime($end_time)]];
            }
            if (!empty($leave_name)) {//请假名称
                $where_4['a.name'] = ['like', "%{$leave_name}%"];
            }
            $res = M('com_leave a')
                ->join('users b', 'b.id=a.user_id', 'left')
                ->join('com_department c', 'c.id=b.department_id', 'left')
                ->field('a.id,a.reason,a.start_time,a.create_time
            ,a.type,a.day,a.hour,a.deduct_marks,a.fixed_deduct,a.status
            ,b.name user_name,c.name department_name')
                ->where($where_4)
                ->where($where_4_a)
                ->order('a.create_time desc')
                ->paginate(11, false, page_param());
            $count = M('com_leave a')
                ->where($where_4)
                ->where($where_4_a)
                ->count();
        }
        $count_page = ceil($count / 11);
        $list = $res->items();
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                if (isset($value['create_time'])) {
                    $list[$key]['create_time'] = date('Y-m-d', $value['create_time']);
                }
                if (isset($value['apply_end_time'])) {
                    $list[$key]['apply_end_time'] = date('Y-m-d H:i:s', $value['apply_end_time']);
                }
                if (isset($value['end_time'])) {
                    $list[$key]['end_time'] = date('Y-m-d H:i:s', $value['end_time']);
                }
                if (isset($value['start_time'])) {
                    $list[$key]['start_time'] = date('Y-m-d', $value['start_time']);
                }
            }
        }
        $time_end = microtime(true);
        $time = $time_end - $time_start;
        $data = [
            'list' => $list,
            'page' => (int)$page,
            'count_page' => $count_page,
            'count' => $count,
            'time'=>$time
        ];
        return return_json(0, '获取成功', $data);
    }

    //任务详情
    public function task_info()
    {    
        $id = I('id', 0);
        if (empty($id)) {
            return return_json(1, 'id不能为空');
        }
        //任务info
        $res = M('com_task a')
            ->join('users b', 'b.id=a.first_check_user_id', 'left')
            ->join('users c', 'c.id=a.last_check_user_id', 'left')
            ->join('users d', 'd.id=a.record_user_id', 'left')
            ->join('users f', 'f.id=a.principal_user_id', 'left')
            ->join('com_department g', 'g.id=f.department_id', 'left')
            ->where('a.id', $id)
            ->field('a.name,a.apply_integral,a.end_time,a.apply_end_time,a.status
            ,a.del_type,a.del_integral,a.del_integral_double,a.double_max,a.reject_type,a.check_status
            ,a.create_time,a.first_check_time,a.last_check_time,a.type,a.first_check_opinion,a.last_check_opinion
            ,f.name principal_name,g.name department_name,b.name first_name,c.name last_name,d.name record_name,a.principal_user_id,a.content
            ,a.first_check_user_id,a.last_check_user_id,a.record_user_id,a.id')
            ->find();
        if (!empty($res['end_time'])) {
            $res['end_time'] = date('Y-m-d H:i', $res['end_time']);
        }
        if (!empty($res['apply_end_time'])) {
            $res['apply_end_time'] = date('Y-m-d H:i', $res['apply_end_time']);
        }
        if (!empty($res['create_time'])) {
            $res['create_time'] = date('Y-m-d H:i:s', $res['create_time']);
        }
        if (!empty($res['first_check_time'])) {
            $res['first_check_time'] = date('Y-m-d H:i:s', $res['first_check_time']);
        }
        if (!empty($res['last_check_time'])) {
            $res['last_check_time'] = date('Y-m-d H:i:s', $res['last_check_time']);
        }
        if ($res['type'] == 2) {
            //悬赏范围
            $list = M('com_task_relation a')
                ->join('users b', 'b.id=a.user_id', 'left')
                ->where('a.task_id', $id)
                ->column('b.name');
            $not_apply = M('com_task_relation a')
                ->join('users b', 'b.id=a.user_id', 'left')
                ->where(['a.task_id'=>$id,'a.status' =>0])
                ->field('a.user_id,b.name')
                ->select();
            $res['not_apply'] = $not_apply;
            $list = implode(',', $list);
            $res['scope'] = $list;
            //报名人
            $apply = M('com_task_relation a')
                ->join('users b', 'b.id=a.user_id', 'left')
                ->join('com_department c', 'c.id=b.department_id', 'left')
                ->where(['a.task_id' => $id, 'a.status' => 1])
                ->field('b.name,c.name department_name,a.apply_time,a.reason,a.user_id')
                ->select();
            if (!empty($apply)) {
                foreach ($apply as $key => $value) {
                    if (!empty($value['apply_time'])) {
                        $apply[$key]['apply_time'] = date('Y-m-d H:i:s', $value['apply_time']);
                    }
                }
            }
            $apply_count = count($apply);
            $res['apply'] = $apply;
            $res['apply_count'] = $apply_count;
        }
        //参与人列表
        $take = M('com_task_relation_take a')
            ->join('users b', 'b.id=a.user_id', 'left')
            ->join('com_department c', 'c.id=b.department_id', 'left')
            ->where(['a.task_id' => $id])
            ->field('b.name,b.id user_id,c.name department_name')
            ->select();
        if (!empty($take)) {
            foreach ($take as $key => $value) {
                $take[$key]['type'] = 1;
            }
        }
        $data = [
            'name' => $res['principal_name'],
            'user_id'=>$res['principal_user_id'],
            'department_name' => $res['department_name'],
            'type' => 2,
        ];
        $take[] = $data;
        $take_count = count($take);
        $res['take_count'] = $take_count;
        $res['take'] = $take;
        return return_json(0, '获取成功', $res);
    }

    //公告详情
    public function notice_info()
    {
        $id = I('id', 0);
        if (empty($id)) {
            return return_json(1, '公告id不能为空');
        }
        $uid = $this->user_id;
        $res = M('com_notice a')
            ->join('users b', 'b.id=a.record_user_id', 'left')
            ->join('users c', 'c.id=a.first_check_user_id', 'left')
            ->join('users d', 'd.id=a.last_check_user_id', 'left')
            ->where('a.id', $id)
            ->field('a.*,b.name record_name,c.name first_name,d.name last_name')
            ->find();
        $end_time = $res['end_time'];//截止时间
        //查询用户阅读状态
        unset($res['com_id']);
//        unset($res['id']);
        if (!empty($res['end_time'])) {
            $res['end_time'] = date('Y-m-d H:i:s', $res['end_time']);
        }
        if (!empty($res['create_time'])) {
            $res['create_time'] = date('Y-m-d H:i:s', $res['create_time']);
        }
        if (!empty($res['first_check_time'])) {
            $res['first_check_time'] = date('Y-m-d H:i:s', $res['first_check_time']);
        }
        if (!empty($res['last_check_time'])) {
            $res['last_check_time'] = date('Y-m-d H:i:s', $res['last_check_time']);
        }
        //公告范围
        $list = M('com_notice_relation a')
            ->join('users b', 'b.id=a.user_id', 'left')
            ->where('a.notice_id', $id)
            ->group('a.user_id')
            ->column('b.name');
        $list = implode(',', $list);
        $res['scope'] = $list;
        //已阅读
        $read = M('com_notice_relation a')
            ->join('users b', 'b.id=a.user_id', 'left')
            ->join('com_department c', 'c.id=b.department_id', 'left')
            ->where(['a.notice_id' => $id, 'a.status' => 1,'a.com_id'=>$this->com_id])
            ->group('a.user_id')
            ->field('b.name,c.name department_name,a.user_id')
            ->select();
        $read_count = count($read);
        $res['read_count'] = $read_count;
        $res['read'] = $read;
        //未阅读
        $not_read = M('com_notice_relation a')
            ->join('users b', 'b.id=a.user_id', 'left')
            ->join('com_department c', 'c.id=b.department_id', 'left')
            ->where(['a.notice_id' => $id, 'a.status' => 0,'a.com_id'=>$this->com_id])
            ->group('a.user_id')
            ->field('b.name,c.name department_name,a.user_id')
            ->select();
        if ($end_time >= time()) {
            $user_status = 0;
            foreach ($not_read as $key => $value) {
                if ($value['user_id'] == $uid) {
                    $user_status = 1;
                }
            }
            if ($user_status == 1) {
                //阅读奖分
                $info = M('com_notice')->where('id', $id)->find();
                $info['user_id'] = $uid;
                SendIntegralNew::add_record_integral($info, $info['read_integral'], 0, 20, true);
                //更新用户阅读状态
                M('com_notice_relation')->where(['user_id'=>$uid,'notice_id'=>$id])->update(['status' => 1]);
            }
        }else{
            $user_status = 0;
            foreach ($not_read as $key => $value) {
                if ($value['user_id'] == $uid) {
                    $user_status = 1;
                }
            }
            if ($user_status == 1 && $res['status'] == 2) {
                //阅读扣分
                $info = M('com_notice')->where('id', $id)->find();
                $info['user_id'] = $uid;
                $where_1['notice_id'] = $id;
                $where_1['status'] = 0;
                $notice_user = M('com_notice_relation')->where($where_1)->group('user_id')->select();
                foreach ($notice_user as $k2=>$v2){
                    $info['user_id'] = $v2['user_id'];
                    SendIntegralNew::add_record_integral($info,-abs($info['not_read_integral']),0,22,true);
                }
                //更新公告状态
                M('com_notice')->where('id',$id)->update(['status'=>3]);
            }
        }
        $not_read_count = count($not_read);
        $res['not_read_count'] = $not_read_count;
        $res['not_read'] = $not_read;
        return return_json(0, '获取成功', $res);
    }

    //我的奖票
    public function my_lottery_ticket()
    {
        $uid = $this->user_id;
        $where['a.is_lottery_ticket'] = 1; //奖票事件
        $where['a.is_print'] = 0; //未打印奖票
        $where['a.user_id'] = $uid; //参与人
        $where['c.status'] = 2; //审核通过
        $res = M('com_integral_event_relation_users a')
            ->join('com_integral_prize_buckle_relation_event b', 'b.id=a.event_id', 'left')
            ->join('com_integral_prize_buckle c', 'c.id = b.prize_buckle_id', 'left')
            ->join('users d', 'd.id=c.first_check_user_id', 'left')
            ->join('users e', 'e.id=c.last_check_user_id', 'left')
            ->join('users f', 'f.id=c.record_user_id', 'left')
            ->join('com_event g', 'g.id=b.event_id', 'left')
            ->where($where)
            ->field('a.integral_b,g.name,f.name record_name,d.name first_name,e.name last_name')
            ->select();
        $count = count($res);
        $data = [
            'list' => $res,
            'count' => $count
        ];
        return return_json(0, '获取成功', $data);
    }

    //电子抽奖列表-活动列表
    public function activity()
    {
        $com_id = $this->com_id;
        $uid = $this->user_id;
        $where['a.end_time'] = ['gt', time()];
        $where['a.com_id'] = $com_id;
        $res = M('com_activity a')
            ->where($where)
            ->field('a.id,a.name,a.img,a.apply_sum,a.end_time,apply_max')
            ->order('a.end_time desc')
            ->select();
        if (!empty($res)) {
            foreach ($res as $key => $value) {
                if (!empty($value['img'])) {
                    $res[$key]['img'] = getImageUrl($value['img']);
                }
                if (!empty($value['end_time'])) {
                    $res[$key]['end_time'] = date('Y-m-d', $value['end_time']);
                }
                //报名数量
                $count = M('com_activity_relation_users')->where(['user_id' => $uid, 'activity_id' => $value['id']])->count();
                $res[$key]['count'] = $count;
            }
        }
        return return_json(0, '获取成功', $res);
    }

    //报名 -投入奖票
    public function apply_activity()
    {
        $uid = $this->user_id;
        $activity_id = I('activity_id', 0);//活动id
        $sum = I('sum', 0);//投入奖票数量
        if (empty($activity_id)) {
            return return_json(0, '活动id不能为空');
        }
        if (empty($sum)) {
            return return_json(0, '投入数量不能为空');
        }
        //查询用户可投数量
        $where['a.is_lottery_ticket'] = 1; //奖票事件
        $where['a.is_print'] = 0; //未打印奖票
        $where['a.user_id'] = $uid; //参与人
        $where['c.status'] = 2; //审核通过
        $list = M('com_integral_event_relation_users a')
            ->join('com_integral_prize_buckle_relation_event b', 'b.id=a.event_id', 'left')
            ->join('com_integral_prize_buckle c', 'c.id = b.prize_buckle_id', 'left')
            ->where($where)
            ->field('a.id')
            ->select();
        $count = count($list);
        if ($count == 0) {
            return return_json(1, '没有可用的奖票');
        } else {
            if ($sum > $count) {
                return return_json(1, '超过可用的奖票数量');
            }
        }
        //活动信息
        $res = M('com_activity ')
            ->where(['id' => $activity_id])
            ->find();
        //可投数量
        $able = $res['apply_max'] - $res['apply_sum'];
        if ($sum > $able) {
//            return return_json(1, '超过最大的可投奖票数量');
        }
        //投奖操作
        DB::startTrans();
        try {
            //活动表修改已报名数
            M('com_activity')->where('id', $activity_id)->setInc('apply_sum', $sum);
            $i = 0;
            foreach ($list as $key => $value) {
                if ($i < $sum) {
                    //改变用户奖票打印状态
                    M('com_integral_event_relation_users')->where('id', $value['id'])->update(['is_print' => 1]);
                    //添加用户报名
                    $data = [
                        'com_id' => $this->com_id,
                        'activity_id' => $activity_id,
                        'user_id' => $uid,
                        'event_id' => $value['id'],
                    ];
                    M('com_activity_relation_users')->insert($data);
                    $i++;
                }
            }
            DB::commit();
            return return_json(0);
        } catch (\Exception $e) {
            DB::rollback();
            return return_json(1, $e->getMessage());
        }
    }

    //公告
    public function notice_unread()
    {
        $type = I('type', 1); //1 未读公告 2已读公告
        $uid = $this->user_id;
        $where['b.user_id'] = $uid;
        $where['a.status'] = ['in',[2,3]];
        $page = I('page', 1);
        if ($type == 1) {
            $where['b.status'] = 0;
        } else {
            $where['b.status'] = 1;
        }
        $res = M('com_notice a')
            ->join('com_notice_relation b', 'b.notice_id = a.id', 'left')
            ->where($where)
            ->order('a.create_time desc')
            ->field('a.id,a.name,a.content,a.read_integral,a.not_read_integral,a.status')
            ->paginate(11, false, page_param());
        $count = M('com_notice a')
            ->join('com_notice_relation b', 'b.notice_id = a.id', 'left')
            ->where($where)
            ->count();
        $count_page = ceil($count / 11);
        $list = $res->items();
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                $read_count = M('com_notice_relation')->where(['notice_id' => $value['id'], 'status' => 1])->count();
                $list[$key]['read_count'] = $read_count;
            }
        }
        $data = [
            'list' => $list,
            'page' => (int)$page,
            'count_page' => $count_page,
            'count' => $count
        ];
        return return_json(0, '获取成功', $data);
    }

    //我发布的公告
    public function my_push_notice()
    {
        $uid = $this->user_id;
        $page = I('page', 1);
        $status = I('status', -1);//审核状态 -1全部  0待初审   1待终审  2公示中  3已截止 4拟稿
        $where['a.record_user_id'] = $uid;
        if ($status != -1) {
            $where['a.status'] = $status;
        }
        $res = M('com_notice a')
            ->where($where)
            ->order('a.create_time desc')
            ->field('a.id,a.name,a.content,a.read_integral,a.not_read_integral,a.create_time,a.status')
            ->paginate(11, false, page_param());
        $count = M('com_notice a')
            ->where($where)
            ->count();
        $count_page = ceil($count / 11);
        $list = $res->items();
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                if (!empty($value['create_time'])) {
                    $list[$key]['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
                }
            }
        }
        $data = [
            'list' => $list,
            'page' => (int)$page,
            'count_page' => $count_page,
            'count' => $count
        ];
        return return_json(0, '获取成功', $data);
    }

    //公告发布
    public function notice_push()
    {
        $params = input();
        $result = $this->validate(
            $params,
            ['name' => 'require|max:50',
            ],
            ['name.require' => '公告名称必填',
                'name.max' => '名称最多50个字符',
            ]
        );
        if (true !== $result) {
            return return_json(1, $result);
        }
        if ($params['first_check_user_id'] == $params['last_check_user_id']) {
            return return_json(1, '初审和终审人不能相同');
        }
        DB::startTrans();
        try {
            $data_take = isset($params['take']) ? json_decode($params['take'], true) : [];
            unset($params['take']);
            $params['record_user_id'] = $this->user_id;
            if ($params['record_user_id'] == $params['first_check_user_id']) {//初审和记录人相同默认初审通过
                $params['status'] = 1;
                $params['first_check_time'] = time();
            }
            $params['create_time'] = time();
            $params['end_time'] = strtotime($params['end_time']);
            $params['com_id'] = $this->com_id;
            $data = [
                'com_id' => $this->com_id,
                'name' => $params['name'],
                'content' => $params['content'],
                'end_time' => $params['end_time'],
                'read_integral' => $params['read_integral'],
                'not_read_integral' => $params['not_read_integral'],
                'first_check_user_id' => $params['first_check_user_id'],
                'last_check_user_id' => $params['last_check_user_id'],
                'record_user_id' => $params['record_user_id'],
                'create_time' => $params['create_time'],
                'status' => isset($params['status']) ? $params['status'] : 0,
                'first_check_time' => isset($params['first_check_time']) ? $params['first_check_time'] : 0,
                'first_check_opinion' => isset($params['first_check_opinion']) ? $params['first_check_opinion'] : '',
            ];
            if(empty($params['id'])) {
                $id = M('com_notice')->insertGetId($data);
                if (!empty($data_take)) {
                    $data_add = [];
                    foreach ($data_take as $key => $value) {
                        $data_add[] = [
                            'com_id' => $this->com_id,
                            'notice_id' => $id,
                            'user_id' => $value,
                        ];
                    }
                    M('com_notice_relation')->insertAll($data_add);
                } else {
                    return return_json(1, '消息推送用户不能为空');
                }
            }else{
                M('com_notice')->where('id',$params['id'])->update($data);
                $id = $params['id'];
                //删除用户
                M('com_notice_relation')->where('id',$id)->delete();
                if (!empty($data_take)) {
                    $data_add = [];
                    foreach ($data_take as $key => $value) {
                        $data_add[] = [
                            'com_id' => $this->com_id,
                            'notice_id' => $id,
                            'user_id' => $value,
                        ];
                    }
                    M('com_notice_relation')->insertAll($data_add);
                } else {
                    return return_json(1, '消息推送用户不能为空');
                }
            }
            DB::commit();//提交
            return return_json(0);
        } catch (\Exception $e) {
            DB::rollback();//回滚
            return return_json(1, $e->getMessage());
        }
    }

    //我的任务-报名任务
    public function my_apply_task()
    {
        $page = I('page', 1);
        $type = I('type', 1);//1未报名 2已报名
        $uid = $this->user_id;
        $where['b.user_id'] = $uid;
        $where['a.status'] = 2;//报名中
        if ($type == 1) {
            $where['b.status'] = 0;
        } else {
            $where['b.status'] = 1;
        }
        $res = M('com_task a')
            ->join('com_task_relation b', 'b.task_id=a.id', 'left')
            ->where($where)
            ->field('a.id,a.name,a.content,a.apply_integral,a.apply_end_time')
            ->paginate(11, false, page_param());
        $count = M('com_task a')
            ->join('com_task_relation b', 'b.task_id=a.id', 'left')
            ->where($where)
            ->count();
        $count_page = ceil($count / 11);
        $list = $res->items();
        foreach ($list as $key => $value) {
            $apply_count = M('com_task_relation')->where(['task_id' => $value['id'], 'status' => 1])->count();
            $list[$key]['apply_count'] = $apply_count;
            if (!empty($value['apply_end_time'])) {
                $list[$key]['apply_end_time'] = date('Y-m-d H:i:s', $value['apply_end_time']);
            }
        }
        $data = [
            'list' => $list,
            'page' => (int)$page,
            'count_page' => $count_page,
            'count' => $count
        ];
        return return_json(0, '获取成功', $data);

    }

    //我的任务-我参与或我负责的任务
    public function task_take()
    {
        $page = I('page', 1);
        $uid = $this->user_id;
        $type_cate = I('type_cate', 1);//1我参与的任务  2 我负责的任务
        $type = I('type', 0);//1指定任务  2悬赏任务 默认全部0
        $status = I('status', -1);//状态 2报名中 3进行中 4已提交
        $time = I('time', '');//时间 默认空
        if (!empty($time)) {
            $start_time = strtotime($time);
            $end_time = strtotime("+1 month -1 day", $start_time);
            $where['a.end_time'] = ['between', [$start_time, $end_time]];
        }
        if (!empty($type)) {
            $where['a.type'] = $type;
        }
        if ($status == -1) {
            $where['a.status'] = ['in', [2, 3, 4]];
        } else {
            $where['a.status'] = $status;
        }
        if ($type_cate == 1) {
            $where['c.user_id'] = $uid;
        } else {
            $where['a.principal_user_id'] = $uid;
        }
        $res = M('com_task a')
            ->join('users b', 'b.id=a.principal_user_id', 'left')
            ->join('com_task_relation_take c', 'c.task_id=a.id', 'left')
            ->join('users d', 'd.id = a.record_user_id', 'left')
            ->where($where)
            ->group('a.id')
            ->field('a.id,d.name record_name,a.type,a.name,a.apply_integral,a.apply_end_time,a.end_time
            ,a.status,b.name principal_name,a.del_type,a.del_integral,a.del_integral_double
            ,a.double_max,a.principal_user_id')
            ->order('a.create_time desc')
            ->paginate(11, false, page_param());
        $count = M('com_task a')
            ->join('users b', 'b.id=a.principal_user_id', 'left')
            ->join('com_task_relation_take c', 'c.task_id=a.id', 'left')
            ->where($where)
            ->group('a.id')
            ->count();
        $count_page = ceil($count / 11);
        $list = $res->items();
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                if (!empty($value['end_time'])) {
                    $list[$key]['end_time'] = date('Y-m-d', $value['end_time']);
                }
                if (!empty($value['apply_end_time'])) {
                    $list[$key]['apply_end_time'] = date('Y-m-d', $value['apply_end_time']);
                }
            }
        }
        $data = [
            'list' => $list,
            'page' => (int)$page,
            'count_page' => $count_page,
            'count' => $count
        ];
        return return_json(0, '获取成功', $data);

    }

    //我发布的任务
    public function my_send_task()
    {
        $page = I('page', 1);
        $uid = $this->user_id;
        $type_cate = I('type_cate', 1);//进行中 2 审核中
        $type = I('type', 0);//1指定任务  2悬赏任务 默认全部0
        $status = I('status', -1);//状态 0 待初审  1待终审 2报名中 3进行中 4已提交 5拟稿 6已过期
        $time = I('time', 0);//时间 默认空
        $where['a.record_user_id'] = $uid;//我发布的
        if (!empty($time)) {
            $start_time = strtotime($time);
            $end_time = strtotime("+1 month -1 day", $start_time);
            $where['a.end_time'] = ['between', [$start_time, $end_time]];
        }
        if (!empty($type)) {
            $where['a.type'] = $type;
        }
        if ($type_cate == 1) {
            $where['a.status'] = ['in', [2, 3, 4]];
        } else {
            $where['a.status'] = ['in', [0, 1, 5]];
        }
        if ($status != -1) {
            if ($status == 6) {
                $where['a.status'] = 3;
                $where['a.end_time'] = ['lt', time()];
            } else {
                if ($status == 3) {
                    $where['a.end_time'] = ['gt', time()];
                }
                $where['a.status'] = $status;
            }
        }
        $res = M('com_task a')
            ->join('users b', 'b.id=a.principal_user_id', 'left')
            ->join('com_task_relation_take c', 'c.task_id=a.id', 'left')
            ->join('users d', 'd.id = a.record_user_id', 'left')
            ->join('users e', 'e.id = a.first_check_user_id', 'left')
            ->join('users f', 'f.id = a.last_check_user_id', 'left')
            ->where($where)
            ->group('a.id')
            ->field('a.id,d.name record_name,a.type,a.name,a.apply_integral,a.apply_end_time,a.end_time
            ,a.status,b.name principal_name,e.name first_name,f.name last_name,a.del_type,a.del_integral,a.del_integral_double
            ,a.double_max,a.principal_user_id')
            ->order('a.create_time desc')
            ->paginate(11, false, page_param());
        $count = M('com_task a')
            ->join('users b', 'b.id=a.principal_user_id', 'left')
            ->join('com_task_relation_take c', 'c.task_id=a.id', 'left')
            ->where($where)
            ->group('a.id')
            ->count();
        $count_page = ceil($count / 11);
        $list = $res->items();
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                if (!empty($value['end_time'])) {
                    $list[$key]['end_time'] = date('Y-m-d', $value['end_time']);
                }
                if (!empty($value['apply_end_time'])) {
                    $list[$key]['apply_end_time'] = date('Y-m-d', $value['apply_end_time']);
                }
            }
        }
        $data = [
            'list' => $list,
            'page' => (int)$page,
            'count_page' => $count_page,
            'count' => $count
        ];
        return return_json(0, '获取成功', $data);
    }

    //添加任务或者拟稿编辑添加
    public function add_task()
    {
        $uid = $this->user_id;
        $com_id = $this->com_id;
        $params = input();
        $result = $this->validate(
            $params,
            [
                'name' => 'require|max:50',
                'del_type' => 'require',
            ],
            [
                'name.require' => '标题必填',
                'del_type.require' => '扣分类型不能为空',
                'name.max' => '标题最多50个字符',
            ]
        );
        if (true !== $result) {
            return return_json(1, $result);
        }
        if ($params['first_check_user_id'] == $params['last_check_user_id']) {
            return return_json(1, '初审和终审人不能相同');
        }
        if (isset($params['take']) && !empty($params['take'])) {
            $params['take'] = json_decode($params['take'], true);
        }
        if (isset($params['push']) && !empty($params['push'])) {
            $params['push'] = json_decode($params['push'], true);
        }
        if (in_array($params['principal_user_id'], $params['take'])) {//负责人不能在参与人里面
            return return_json(1, '负责人不能在参与人里面');
        }
        DB::startTrans();//开启事务
        try {
            $data_take = $params['take'];
            unset($params['take']);
            $data_push = [];
            if ($params['type'] == 2) {
                if (!isset($params['push'])) {
                    return return_json(1, '消息推送范围不能为空');
                }
                if (in_array($params['principal_user_id'], $params['push'])) {//负责人不能在推送人里面
                    return return_json(1, '负责人不能在推送人里面');
                }
                $data_push = $params['push'];
                unset($params['push']);
            }

            $params['record_user_id'] = $uid;
            if ($params['record_user_id'] == $params['first_check_user_id']) {//初审和记录人相同默认初审通过
                $params['status'] = 1;
                $params['first_check_time'] = time();
            }else{
                $params['status'] = 0;
                $params['first_check_time'] = 0;
            }
            if (!empty($params['apply_end_time'])) {
                $params['apply_end_time'] = strtotime($params['apply_end_time']);
            }
            $params['create_time'] = time();
            $params['end_time'] = strtotime($params['end_time']);
            $params['com_id'] = $com_id;
            $data = [
                'com_id' => $com_id,
                'name' => $params['name'],
                'content' => $params['content'],
                'type' => $params['type'],
                'principal_user_id' => $params['principal_user_id'],
                'end_time' => $params['end_time'],
                'del_integral' => isset($params['del_integral']) ? $params['del_integral'] : 0,
                'del_type' => $params['del_type'],
                'del_integral_double' => isset($params['del_integral_double']) ? $params['del_integral_double'] : 0,
                'double_max' => isset($params['double_max']) ? $params['double_max'] : 0,
                'first_check_user_id' => $params['first_check_user_id'],
                'last_check_user_id' => $params['last_check_user_id'],
                'record_user_id' => $params['record_user_id'],
                'apply_integral' => isset($params['apply_integral']) ? $params['apply_integral'] : 0,
                'apply_end_time' => isset($params['apply_end_time']) ? $params['apply_end_time'] : 0,
                'status' => isset($params['status']) ? $params['status'] : 0,
                'create_time' => $params['create_time'],
                'first_check_time' => isset($params['first_check_time']) ? $params['first_check_time'] : 0,
                'first_check_opinion' => isset($params['first_check_opinion']) ? $params['first_check_opinion'] : '',
            ];
            if(empty($params['id'])) {
                //新增
                $id = M('com_task')->insertGetId($data);
                if (!empty($data_push)) {
                    $data_add_1 = [];
                    foreach ($data_push as $key => $value) {
                        $data_add_1[] = [
                            'com_id' => $this->com_id,
                            'task_id' => $id,
                            'user_id' => $value,
                        ];
                    }
                    //新增可以报名的人
                    M('com_task_relation')->insertAll($data_add_1);
                }
                if (!empty($data_take)) {
                    $data_add = [];
                    foreach ($data_take as $key => $value) {
                        $data_add[] = [
                            'com_id' => $this->com_id,
                            'task_id' => $id,
                            'user_id' => $value,
                        ];
                    }
                    //新增参与人
                    M('com_task_relation_take')->insertAll($data_add);
                }
            }else{
                //编辑
                M('com_task')->where('id',$params['id'])->update($data);
                //删除报名表
                M('com_task_relation')->where('task_id',$params['id'])->delete();
                //删除参与人表
                M('com_task_relation_take')->where('task_id',$params['id'])->delete();
                $id = $params['id'];
                if (!empty($data_push)) {
                    $data_add_1 = [];
                    foreach ($data_push as $key => $value) {
                        $data_add_1[] = [
                            'com_id' => $this->com_id,
                            'task_id' => $id,
                            'user_id' => $value,
                        ];
                    }
                    //新增可以报名的人
                    M('com_task_relation')->insertAll($data_add_1);
                }
                if (!empty($data_take)) {
                    $data_add = [];
                    foreach ($data_take as $key => $value) {
                        $data_add[] = [
                            'com_id' => $this->com_id,
                            'task_id' => $id,
                            'user_id' => $value,
                        ];
                    }
                    //新增参与人
                    M('com_task_relation_take')->insertAll($data_add);
                }
            }
            $data_message = [];
            //记录人
            $data_message[] = [
                'title' => '您有任务记录提交审核',
                'user_id' => $uid,
                'cate_type' => 2,//任务消息
                'type' => 2,//任务
                'relation_id' => $id
            ];
            if($params['status'] == 1){
                //终审人
                $data_message[] = [
                    'title' => '您有任务记录待审核(终审)',
                    'user_id' => $params['last_check_user_id'],
                    'cate_type' => 1,//审核消息
                    'type' => 2,//
                    'relation_id' => $id
                ];
            }else {
                //初审人
                $data_message[] = [
                    'title' => '您有任务记录待审核(初审)',
                    'user_id' => $params['first_check_user_id'],
                    'cate_type' => 1,//审核消息
                    'type' => 2,//
                    'relation_id' => $id
                ];
            }
            Message::send_message_list($data_message);
            DB::commit();//提交
            return return_json(0);
        } catch (\Exception $e) {
            DB::rollback();//回滚
            return return_json(1, $e->getMessage());
        }
    }

    //多图上传
    public function upload_image()
    {
        set_time_limit(0);
        $uptypes = array(
            'image/jpg',
            'image/jpeg',
            'image/png',
            'image/pjpeg',
            'image/gif',
            'image/bmp',
            'image/x-png',
            'multipart/form-data',
        );
        $max_file_size = 10000000;     //上传文件大小限制, 单位BYTE
        $destination_folder = ROOT_PATH . "public/uploads/" . date('Y') . "/" . date('m') . "/" . date('d') . "/"; //上传文件路径
        $file_a = $_FILES;
        if (!isset($file_a)) {
            return return_json(1, '图片不存在', null);
        }
        $count = count($file_a);
        $data = [];
        for ($i = 0; $i < $count; $i++) {
            $file = $file_a['file' . $i];
            if (!is_uploaded_file($file['tmp_name'])) //是否存在文件
            {
                return return_json(1, '图片不存在' . $i, null);
            }
            if ($max_file_size < $file["size"]) //检查文件大小
            {
                return return_json(1, '文件太大', null);
            }
            if (!in_array($file["type"], $uptypes)) //检查文件类型
            {
                return return_json(1, "文件类型不符!" . $file["type"], null);
            }
            if (!file_exists($destination_folder)) {
                @mkdir($destination_folder, 0777, true);
            }
            $filename = $file["tmp_name"];
            $pinfo = pathinfo($file["name"]);
            $ftype = $pinfo['extension'];
            $destination1 = str_shuffle(time() . rand(111111, 999999)) . "." . $ftype;
            $destination = $destination_folder . $destination1;
            if (!move_uploaded_file($filename, $destination)) {
                return return_json(1, '移动文件出错', null);
            }
            $data[] = [
                'url' => getImageUrl("/uploads/" . date('Y') . "/" . date('m') . "/" . date('d') . "/" . $destination1)
            ];
        }
        return return_json(0, '上传成功', $data);

    }

    //奖扣详情
    public function prize_buckle_info()
    {
        $uid = $this->user_id;
        $type = I('type', 1);//奖扣类型  1日统计  2月统计  3年统计 默认1
        $time = I('time', '');//时间
        if (empty($time)) {
            return return_json(1, '时间不能为空');
        }
        if ($type == 1) {
            $start_time = strtotime($time);
            $end_time = $start_time + 24 * 3600 - 1;
            $count_time_start = strtotime(date('Y-m-01', $start_time));
            $count_time_end = strtotime("+1 month", $count_time_start)-1;
            $max_day = date('d', $count_time_end);
        } elseif ($type == 2) {
            $start_time = strtotime($time . '-01-01');
            $end_time = strtotime('+1 month', $start_time)-1;
            $count_time_start = strtotime(date('Y-01-01', $start_time));
            $count_time_end = strtotime("+1 year", $count_time_start)-1;
            $max_month = 12;
        } elseif ($type == 3) {
            $start_time = strtotime($time . '0101');
            $end_time = strtotime('+1 year', $start_time)-1;
            $count_time_end = $end_time;
            $count_time_start = strtotime("-3 years", $count_time_end);
            $max_year = date('Y', $start_time);
            $min_year = $max_year - 3;
        }
        //奖扣详情状况
        $where_1['a.prize_buckle_time'] = ['between', [$count_time_start, $count_time_end]];//奖扣时间
        $where_1['a.first_check_user_id'] = $uid; //初审人
        $where_1['a.status'] = 2; //审核通过
        $where_1['c.is_cancellation'] = 0; //未作废
        $res = M('com_integral_prize_buckle a')
            ->join('com_integral_prize_buckle_relation_event b','b.prize_buckle_id=a.id','right')
            ->join('com_integral_event_relation_users c','c.event_id=b.id','right')
            ->where($where_1)
            ->field('COALESCE(sum(IF(c.integral_b>0,IF(c.piece_rate=0,c.integral_b,c.integral_b*c.piece_rate),0)),0) integral_b_add,COALESCE(sum(IF(c.integral_b<0,IF(c.piece_rate=0,c.integral_b,c.integral_b*c.piece_rate),0)),0) integral_b_del,COALESCE(count(c.id),0) people_sum')
            ->find();
        if ($res['integral_b_add'] == 0 || $res['integral_b_del'] == 0) {
            $rate = 0;
        } else {
            $rate = round($res['integral_b_del'] / $res['integral_b_add'] * 100);
        }
        //奖扣详情
        $prize_buckle_info = [
            'total_prize' => $res['integral_b_add'],
            'total_buckle' => $res['integral_b_del'],
            'people_sum' => $res['people_sum'],
            'rate' => abs($rate),
        ];
        $where_1_a['a.prize_buckle_time'] = ['between', [$count_time_start, $count_time_end]];//奖扣时间
        $where_1_a['a.first_check_user_id'] = $uid; //初审人
        $where_1_a['a.status'] = 2; //审核通过
        $where_1_a['c.is_cancellation'] = 0; //未作废
        $data_total = M('com_integral_prize_buckle a')
            ->join('com_integral_prize_buckle_relation_event b','b.prize_buckle_id=a.id','right')
            ->join('com_integral_event_relation_users c','c.event_id=b.id','right')
            ->where($where_1_a)
            ->group('a.prize_buckle_time')
            ->field('a.prize_buckle_time,COALESCE(sum(IF(c.integral_b>0,IF(c.piece_rate=0,c.integral_b,c.integral_b*c.piece_rate),0)),0) integral_b_add,COALESCE(sum(IF(c.integral_b<0,IF(c.piece_rate=0,c.integral_b,c.integral_b*c.piece_rate),0)),0) integral_b_del,COALESCE(count(c.id),0) people_sum')
            ->select();
//        $data_prize=[];//奖分趋势
//        $data_buckle=[];//扣分趋势
//        $data_people=[];//人次趋势
//        $data_rate=[];//比例趋势
        $data = [];
        if ($type == 1) {
            foreach ($data_total as $key => $value) {
                $data_total[$key]['day'] = date('d', $value['prize_buckle_time']);
            }
            for ($i = 1; $i <= $max_day; $i++) {
                $prize = 0;
                $buckle = 0;
                $people = 0;
                foreach ($data_total as $value) {
                    if ($value['day'] == $i) {
                        $prize += $value['integral_b_add'];
                        $buckle += $value['integral_b_del'];
                        $people += $value['people_sum'];
                    }
                }
                if ($prize == 0 || $buckle == 0) {
                    $rate = 0;
                } else {
                    $rate = round($buckle / $prize * 100);
                }
                $data[] = [
                    'time' => $i,
                    'data_prize' => $prize,
                    'data_buckle' => $buckle,
                    'data_people' => $people,
                    'data_rate' => abs($rate),
                ];
            }
        } elseif ($type == 2) {
            foreach ($data_total as $key => $value) {
                $data_total[$key]['month'] = date('m', $value['prize_buckle_time']);
            }
            for ($i = 1; $i <= $max_month; $i++) {
                $prize = 0;
                $buckle = 0;
                $people = 0;
                foreach ($data_total as $value) {
                    if ($value['month'] == $i) {
                        $prize += $value['integral_b_add'];
                        $buckle += $value['integral_b_del'];
                        $people += $value['people_sum'];
                    }
                }
                if ($prize == 0 || $buckle == 0) {
                    $rate = 0;
                } else {
                    $rate = round($buckle / $prize * 100);
                }
                $data[] = [
                    'time' => $i,
                    'data_prize' => $prize,
                    'data_buckle' => $buckle,
                    'data_people' => $people,
                    'data_rate' => abs($rate),
                ];
            }
        } elseif ($type == 3) {
            foreach ($data_total as $key => $value) {
                $data_total[$key]['year'] = date('Y', $value['prize_buckle_time']);
            }
            for ($i = $min_year; $i <= $max_year; $i++) {
                $prize = 0;
                $buckle = 0;
                $people = 0;
                foreach ($data_total as $value) {
                    if ($value['year'] == $i) {
                        $prize += $value['integral_b_add'];
                        $buckle += $value['integral_b_del'];
                        $people += $value['people_sum'];
                    }
                }
                if ($prize == 0 || $buckle == 0) {
                    $rate = 0;
                } else {
                    $rate = round($buckle / $prize * 100);
                }
                $data[] = [
                    'time' => $i,
                    'data_prize' => $prize,
                    'data_buckle' => $buckle,
                    'data_people' => $people,
                    'data_rate' => abs($rate),
                ];
            }
        }
        //判断用户当月是否有奖扣任务
        $res = M('com_prize_buckle_config_relation_users')->where('user_id', $uid)->find();
        if (empty($res)) {
            $is_prize_buckle_task = 0;
        } else {
            $is_prize_buckle_task = 1;
        }
        //判断用户是否有奖扣权限
        $res_a = M('com_prize_buckle_relation_users')->where('user_id', $uid)->find();
        if (empty($res_a)) {
            $is_prize_buckle = 0;
        } else {
            $is_prize_buckle = 1;
        }
        $data_a = [
            'prize_buckle_info' => $prize_buckle_info,
            'list' => $data,
            'is_prize_buckle_task' => $is_prize_buckle_task,
            'is_prize_buckle' => $is_prize_buckle,
        ];
        return return_json(0, '获取成功', $data_a);
    }

    //奖扣明细
    public function prize_buckle_detail()
    {
        $uid = $this->user_id;
        $type = I('type', 1);//奖扣类型  1日统计  2月统计  3年统计 默认1
        $time = I('time', '');//时间
        $page = I('page', 1);
        if (empty($time)) {
            return return_json(1, '时间不能为空');
        }
        if ($type == 1) {
            $start_time = strtotime($time);
            $end_time = $start_time + 24 * 3600 - 1;
        } elseif ($type == 2) {
            $start_time = strtotime($time . '-01');
            $end_time = strtotime('+1 month -1 day', $start_time);
        } elseif ($type == 3) {
            $start_time = strtotime($time . '0101');
            $end_time = strtotime('+1 year -1 day', $start_time);
        }
        //奖扣详情状况
        $where_1['a.prize_buckle_time'] = ['between', [$start_time, $end_time]];//奖扣时间
        $where_1['a.first_check_user_id'] = $uid; //初审人
        $where_1['a.status'] = 2; //审核通过
        $where_1['c.is_cancellation'] = 0; //未作废
        $res = M('com_integral_prize_buckle a')
            ->join('com_integral_prize_buckle_relation_event b','b.prize_buckle_id=a.id','right')
            ->join('com_integral_event_relation_users c','c.event_id=b.id','right')
            ->where($where_1)
            ->field('COALESCE(sum(IF(c.integral_b>0,IF(c.piece_rate=0,c.integral_b,c.integral_b*c.piece_rate),0)),0) integral_b_add,COALESCE(sum(IF(c.integral_b<0,IF(c.piece_rate=0,c.integral_b,c.integral_b*c.piece_rate),0)),0) integral_b_del,COALESCE(count(c.id),0) people_sum')
            ->find();
        if ($res['integral_b_add'] == 0 || $res['integral_b_del'] == 0) {
            $rate = 0;
        } else {
            $rate = round(($res['integral_b_del'] / $res['integral_b_add'])* 100);
        }
        //奖扣详情
        $prize_buckle_info = [
            'total_prize' => $res['integral_b_add'],
            'total_buckle' => $res['integral_b_del'],
            'people_sum' => $res['people_sum'],
            'rate' => abs($rate),
        ];
        $where_2['a.prize_buckle_time'] = ['between', [$start_time, $end_time]];//奖扣时间
        $where_2['a.first_check_user_id'] = $uid; //初审人
        $where_2['a.status'] = 2; //审核通过
        $where_2['c.is_cancellation'] = 0; //未作废
        $res = M('com_integral_prize_buckle a')
            ->join('com_integral_prize_buckle_relation_event b', 'b.prize_buckle_id=a.id', 'right')
            ->join('com_integral_event_relation_users c', 'c.event_id=b.id', 'right')
            ->join('users d', 'd.id=c.user_id', 'left')
            ->join('com_event e', 'e.id=b.event_id', 'left')
            ->order('a.prize_buckle_time desc')
            ->where($where_2)
            ->field('a.prize_buckle_time,d.name,e.name event_name,COALESCE(c.integral_b,0) total_integral')
            ->paginate(11, false, page_param());
        $count = M('com_integral_prize_buckle a')
            ->join('com_integral_prize_buckle_relation_event b', 'b.prize_buckle_id=a.id', 'right')
            ->join('com_integral_event_relation_users c', 'c.event_id=b.id', 'right')
            ->join('users d', 'd.id=c.user_id', 'left')
            ->join('com_event e', 'e.id=b.event_id', 'left')
            ->order('a.prize_buckle_time desc')
            ->where($where_2)
            ->count();
        $count_page = ceil($count / 11);
        $list = $res->items();
        foreach ($list as $key => $value) {
            $list[$key]['prize_buckle_time'] = date('m-d', $value['prize_buckle_time']);
        }
        $data = [
            'prize_buckle_info' => $prize_buckle_info,
            'list' => $list,
            'page' => (int)$page,
            'count_page' => $count_page,
            'count' => $count
        ];
        return return_json(0, '获取成功', $data);
    }

    //奖扣任务
    public function prize_buckle_task()
    {
        $uid = $this->user_id;
        $time = I('time', '');
        if (empty($time)) {
            return return_json(1, '时间不能为空');
        }
        $start = strtotime($time . '-01');
        $end = strtotime('+1 month', $start)-1;
        //查询用户配置
        $sys = M('com_prize_buckle_config_relation_users a')
            ->join('com_prize_buckle_config b', 'a.prize_buckle_id=b.id', 'left')
            ->where('a.user_id', $uid)
            ->field('b.*')
            ->find();
        //判断是否是本月
        if (date('Y-m', time()) == $time) {
            $data = Task::get_prize_buckle_task($uid, $time);
        } else {
            $where_a = [];
            $where_a['user_id'] = $uid;
            $where_a['year_month'] = strtotime($time);
            $res = M('com_prize_buckle_task_log')->where($where_a)->find();
            $num = (int)date('d', $end);
            $man_deduct = $sys['man_deduct'] * $num;
//            if($sys['man_type'] == 1){//日任务
//                $man_deduct = $sys['man_deduct']*$num;
//            }
            //判断是否有记录
            if (empty($res)) {//没有记录
                if ($sys['integral_type'] == 0) {
                    $prize_integral_del = 4 * $sys['integral_reward'];
                    $buckle_integral_del = 4 * $sys['integral_deduct'];
                } else {
                    $prize_integral_del = $sys['integral_reward'];
                    $buckle_integral_del = $sys['integral_deduct'];
                }
                $data = [
                    'prize_integral_target' => $sys['integral_reward'],//奖分目标
                    'buckle_integral_target' => $sys['integral_deduct'],//扣分目标
                    'prize_integral_com' => 0,//奖分完成值
                    'buckle_integral_com' => 0,//扣分完成值
                    'prize_integral_status' => 0,//奖分状态  0未完成  1已完成
                    'buckle_integral_status' => 0,//扣分状态  0未完成 1已完成
                    'prize_integral_del' => $prize_integral_del,//奖分未完成扣分
                    'buckle_integral_del' => $buckle_integral_del,//扣分未完成扣分
                    'rate_target' => $sys['rate'],//奖扣比例目标
                    'rate_com' => 0,//奖扣比例已完成值
                    'rate_status' => 1,//完成状态 0未完成 1已完成
                    'rate_del' => 0,//比例未完成扣分
                    'people_day' => $num,//人次月天数
                    'people_day_total' => $num,//人次统计天数
                    'people_day_not' => $num,//人次未完成天数
                    'people_target' => $sys['rate'],//奖扣人次目标
                    'people_com' => 0,//奖扣人次已完成值
                    'people_del' => $sys['man_deduct'],//人次未完成扣分
                    'people_del_total' => $man_deduct,//人次未完成总扣分
                    'people_status' => 0,//人次状态  0未完成 1已完成
                    'prize_buckle_type' => $sys['integral_type'],//奖扣任务类型 0周任务  1月任务
                    'people_type' => $sys['man_type'],//奖扣人次类型  1日任务  2周任务  3月任务
                    'total_people' => 0,//总人次
                    'total_del_integral' => $prize_integral_del + $buckle_integral_del + $man_deduct,//总扣分
                ];
            } else {//有记录
                //人次统计天数
                //查询当月积分奖扣人次数据
                $where_aa = [];
                $where_aa['a.com_id'] = $this->com_id;
                $where_aa['a.user_id'] = $uid;
                $where_aa['a.is_cancellation'] = 0;
                $where_aa['c.status'] = 2;
                $where_aa['c.prize_buckle_time'] = ['between',[$start,$end]];
                $list_a = M('com_integral_event_relation_users a')
                    ->join('com_integral_prize_buckle_relation_event b','b.id=a.event_id','left')
                    ->join('com_integral_prize_buckle c','c.id=b.prize_buckle_id','left')
                    ->where($where_aa)
                    ->field('a.id,c.prize_buckle_time')
                    ->select();
                $com_sum = 0;
                for($j=$num;$j>=0;$j--) {
                    $aaa = 0;
                    foreach ($list_a as $key => $value) {
                        if(date('d',$value['prize_buckle_time']) == $j){
                            $aaa ++;
                        }
                    }
                    if($aaa < $res['people_target']){
                        $com_sum ++;
                    }
                }
                if($res['people_type'] == 1){

                }
                $data = [
                    'prize_integral_target' => $res['prize_integral_target'],//奖分目标
                    'buckle_integral_target' => $res['buckle_integral_target'],//扣分目标
                    'prize_integral_com' => $res['total_prize_integral'],//奖分完成值
                    'buckle_integral_com' => $res['total_buckle_integral'],//扣分完成值
                    'prize_integral_status' => $res['prize_status'],//奖分状态  0未完成  1已完成
                    'buckle_integral_status' => $res['buckle_status'],//扣分状态  0未完成 1已完成
                    'prize_integral_del' => $res['prize_integral_del'],//奖分未完成扣分
                    'buckle_integral_del' => $res['buckle_integral_del'],//奖分未完成扣分
                    'rate_target' => $res['rate_target'],//奖扣比例目标
                    'rate_com' => $res['total_rate'],//奖扣比例已完成值
                    'rate_status' => $res['rate_status'],//完成状态 0未完成 1已完成
                    'rate_del' => $res['rate_del'],//比例未完成扣分
                    'people_day' => $num,//人次月天数
                    'people_day_total' => $num,//人次统计天数
                    'people_day_not' => $com_sum,//人次未完成天数
                    'people_target' => $res['people_target'],//奖扣人次目标
                    'people_com' => 0,//奖扣人次已完成值
                    'people_del' => $res['people_target_del'],//人次未完成扣分
                    'people_del_total' => $res['people_del'],//人次未完成总扣分
                    'people_status' => $res['people_status'],//人次状态  0未完成 1已完成
                    'prize_buckle_type' => $res['prize_integral_type'],//奖扣任务类型 0周任务  1月任务
                    'total_people' => $res['total_people'],//总人次
                    'total_del_integral' => $res['total_del_integral'],//总扣分
                ];
            }
        }
        return return_json(0, '获取成功', $data);
    }

    //管理层奖扣任务
    public function manage_prize_buckle_task()
    {
        $com_id = $this->com_id;
        $time = I('time', '');
        if (empty($time)) {
            return return_json(1, '时间不能为空');
        }
        //查询用户的
        $data = [];
        if (date('Y-m', time()) == $time) {//当月
            $where['a.com_id'] = $com_id;
            $users = M('com_prize_buckle_config_relation_users a')
                ->join('users b', 'b.id=a.user_id', 'left')
                ->join('com_department c', 'c.id=b.department_id', 'left')
                ->where($where)
                ->field('b.id,b.name,c.name department_name')
                ->select();
            if (empty($users)) {
                return return_json(0);
            }
            foreach ($users as $key => $value) {
                $res = Task::get_prize_buckle_task($value['id'], $time);
                $data[] = [
                    'name' => $value['name'],//用户名称
                    'department_name' => $value['department_name'],//部门名称
                    'total_prize' => $res['prize_integral_com'], //总奖分
                    'total_buckle' => $res['buckle_integral_com'],//总扣分
                    'total_people' => $res['people_sum_now'],//总人次
                    'total_rate' => $res['rate_com'],//比例
                    'prize_buckle_type' => $res['prize_buckle_type'],//奖扣类型 0周任务  1月任务
                    'people_type' => $res['people_type'],//奖扣人次类型 1日 2周  3 月
                    'total_del_integral' => $res['total_del_integral'],//总扣分
                    'prize_status' => $res['prize_integral_status'],//奖分任务状态 0未完成 1已完成
                    'buckle_status' => $res['buckle_integral_status'],//扣分任务状态 0未完成  1已完成
                    'rate_status' => $res['rate_status'], //比例任务状态  0未完 1已完成
                    'people_status' => $res['people_status_now'],//人次任务状态  0未完成  1已完成
                ];
            }
        } else {
            //奖扣任务记录
            $where['a.com_id'] = $com_id;
            $where['a.year'] = date('Y', strtotime($time . '-01'));
            $where['a.month'] = date('m', strtotime($time . '-01'));
            $res = M('com_prize_buckle_task_log a')
                ->join('users b', 'b.id=a.user_id', 'left')
                ->join('com_department c', 'c.id=b.department_id', 'left')
                ->where($where)
                ->field('a.total_prize_integral total_prize,a.total_buckle_integral total_buckle
                ,a.total_people,a.total_rate,a.prize_integral_type prize_buckle_type
                ,a.people_type,a.total_del_integral,a.prize_status,a.buckle_status,a.rate_status,a.people_status
                ,b.id,b.name,c.name department_name')
                ->select();
            $data = $res;
        }
        return return_json(0, '获取成功', $data);
    }

    //个人中心
    public function my_center()
    {
        $uid = $this->user_id;
        $res = M('users')->where('id', $uid)->field('integral_b,name,avatar,base_integral,working_age_integral,department_id')->find();
        //查询是否有奖扣权限
        $res['integral_b'] = SendIntegralNew::statistic_integral(strtotime('2010-01-01'),time(),$uid,0);
        $total_integral = $res['integral_b'] + $res['base_integral'] + $res['working_age_integral'];
        $res_a = M('com_prize_buckle_relation_users a')
            ->join('com_prize_buckle b', 'b.id=a.prize_buckle_id')
            ->where('a.user_id', $uid)
            ->field('integral_b')
            ->find();
        if (empty($res_a)) {
            $prize_integral = 0;
        } else {
            $prize_integral = $res_a['integral_b'];
        }
        //部门排名
//        $where['a.department_id'] = $res['department_id'];
//        $where['b.year_month'] = strtotime(date('Y-m', time()));
//        $where['b.type'] = 0;
//        $where['a.type'] = 1;
//        $users = M('users a')
//            ->join('com_integral_log b', 'b.user_id=a.id', 'left')
//            ->where('a.department_id', $res['department_id'])
//            ->where($where)
//            ->group('a.id')
//            ->field('a.id,coalesce(sum(b.integral_b),0) integral_b')
//            ->select();
        $where1 = [
            'department_id'=>$res['department_id'],
//            'type'=>1,
        ];
        $users = M('users')->where($where1)->field('id')->select();
        $start_time = strtotime(date('Y-m-01', time()));
        $end_time = strtotime('+1 month', $start_time)-1;
        foreach ($users as $key=>&$value){
            $value['integral_b'] = SendIntegralNew::statistic_integral($start_time,$end_time,$value['id'],0);
        }
        //冒泡排序
        $users = $this->data_sort($users, 'integral_b');
        $sort = 1;
        foreach ($users as $key => $value) {
            if ($value['id'] == $uid) {
                $sort = $key + 1;
            }
        }
        $data = [
            'name' => $res['name'],
            'avatar' => getImageUrl($res['avatar']),
            'total_integral' => $total_integral,
            'prize_integral' => $prize_integral,
            'sort' => $sort,
        ];
        return return_json(0, '获取成功', $data);
    }

    //我的消息
    public function my_message()
    {
        $uid = $this->user_id;
        $page = I('page', 1);
        $res = M('com_user_message')
            ->where('user_id', $uid)
            ->order('create_time desc')
            ->paginate(11, false, page_param());
        $count = M('com_user_message')
            ->where('user_id', $uid)
            ->count();
        $count_page = ceil($count / 11);
        $list = $res->items();
        foreach ($list as $key => $value) {
            $list[$key]['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
        }
        $data = [
            'list' => $list,
            'page' => (int)$page,
            'count_page' => $count_page,
            'count' => $count
        ];
        return return_json(0, '获取成功', $data);
    }

    //我的通讯录
    public function my_address_book()
    {
        $com_id = $this->com_id;
        //查询用户部门
        $list = db('com_department')->where(['com_id' => $this->com_id])->field('id,name,pid')->select();
        $users = M('users a')
            ->join('com_department b', 'b.id=a.department_id', 'left')
            ->field('a.id,a.name,b.name department_name,b.id department_id')
            ->where(['a.com_id'=>$com_id,'a.type'=>1])
            ->select();
        $list_a = db('com_department')->where(['com_id' => $this->com_id, 'pid' => 0])->field('id,name')->select();

        foreach ($list_a as $key => $value) {
            $list_a[$key]['users'] = $this->get_book_data($list, $value['id'], $users, 'department_id');
        }
        return return_json(0, '获取成功', $list_a);
    }

    //通讯录递归调用
    public function get_book_data($arr = [], $id = 0, $arr_1 = [], $item)
    {
        $list = [];
        foreach ($arr_1 as $key => $value) {
            if ($value[$item] == $id) {
                $list[] = [
                    'id' => $value['id'],
                    'name' => $value['name'],
                ];
            }
        }
        foreach ($arr as $k => $v) {
            if ($v["pid"] == $id) {
                unset($arr[$k]);
                $list_a = $this->get_book_data($arr, $v["id"], $arr_1, $item);
                $list = array_merge($list, $list_a);
            }
        }
        return $list;
    }

    //通讯录用户详情
    public function book_user_info()
    {
        $user_id = I('user_id', 0);
        if (empty($user_id)) {
            return return_json(1, '用户通讯录用户id不能为空');
        }
        $res = M('users a')->where('a.id', $user_id)
            ->join('com_department b', 'b.id=a.department_id', 'left')
            ->join('com_prize_buckle_relation_users c', 'c.user_id=a.id', 'left')
            ->join('com_prize_buckle d', 'd.id=c.prize_buckle_id', 'left')
            ->field('a.*,b.name department_name,d.name duty_name')
            ->find();
        $total_integral = SendIntegralNew::statistic_integral(strtotime('2010-01-01'),time(),$user_id,0) + $res['base_integral'] + $res['working_age_integral'];
        //固定积分
        $total = M('com_fixed_relation_users a')
            ->join('com_fixed_integral b', 'b.id=a.fixed_id', 'left')
            ->where(['a.user_id' => $user_id])
            ->field('coalesce(sum(b.integral),0) total')
            ->find();
        $data = [
            'avatar' => getImageUrl($res['avatar']),
            'name' => $res['name'],
            'total_integral' => $total_integral,
            'department_name' => $res['department_name'],
            'duty_name' => $res['duty_name'],
            'entry_time' => date('Y-m-d', $res['entry_time']),
            'mobile' => $res['mobile'],
            'email' => $res['email'],
            'fixed_integral' => $total['total']
        ];
        return return_json(0, '获取成功', $data);

    }

    //比例任务详情
    public function rate_task_info()
    {
        $uid = $this->user_id;
        $time = I('time', 0);
        $type = I('type', 1); //1奖分  2扣分  默认1
        if (empty($time)) {
            return return_json(1, '时间不能为空');
        }
        $page = I('page', 1);
        $sys = M('com_prize_buckle_config_relation_users a')
            ->join('com_prize_buckle_config b', 'a.prize_buckle_id=b.id', 'left')
            ->where('a.user_id', $uid)
            ->field('b.*')
            ->find();
        $start = strtotime($time . '-01');
        $end = strtotime('+1 month', $start)-1;
//        $where['first_check_user_id'] = $uid; //初审人
//        $where['prize_buckle_time'] = ['between', [$start, $end]]; //奖扣时间范围
//        $where['status'] = 2; //审核通过
//        $res = M('com_integral_prize_buckle')
//            ->where($where)
//            ->field('COALESCE(sum(integral_b_add),0) integral_b_add
//            ,COALESCE(sum(integral_b_del),0) integral_b_del,COALESCE(sum(people_sum),0) people_sum')
//            ->find();
        $res = SendIntegralNew::statistic_prize_buckle($start,$end,$uid);
        //目标比例
        $rate_target = $sys['rate'];
        $total_prize = $res['integral_b_add'];
        $total_buckle = abs($res['integral_b_del']);
        //总人次
        $total_people = $res['people_sum'];
        //本月比例
        if ($res['integral_b_add'] == 0) {
            $total_rate = 0;
        } else {
            $total_rate = round(abs($res['integral_b_del']) / $res['integral_b_add'], 2) * 100;
        }
        $where = [];
        if ($type == 1) {
            $where['a.integral_b'] = ['gt', 0];
        } else {
            $where['a.integral_b'] = ['lt', 0];
        }
        $where['c.first_check_user_id'] = $uid; //初审人
        $where['c.prize_buckle_time'] = ['between', [$start, $end]]; //奖扣时间范围
        $where['c.status'] = 2; //审核通过
        $where['a.is_cancellation'] = 0; //未作废
        $list_a = M('com_integral_event_relation_users a')
            ->join('com_integral_prize_buckle_relation_event b', 'b.id=a.event_id', 'left')
            ->join('com_integral_prize_buckle c', 'c.id=b.prize_buckle_id', 'left')
            ->join('users d', 'd.id=a.user_id', 'left')
            ->join('com_event e', 'e.id=b.event_id', 'left')
            ->where($where)
            ->order('c.prize_buckle_time desc')
            ->field('c.prize_buckle_time,d.name,e.name event_name,a.integral_b')
            ->paginate(11, false, page_param());
        $count = M('com_integral_event_relation_users a')
            ->join('com_integral_prize_buckle_relation_event b', 'b.id=a.event_id', 'left')
            ->join('com_integral_prize_buckle c', 'c.id=b.prize_buckle_id', 'left')
            ->join('users d', 'd.id=a.user_id', 'left')
            ->join('com_event e', 'e.id=b.event_id', 'left')
            ->where($where)
            ->count();
        $count_page = ceil($count / 11);
        $list = $list_a->items();
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                $list[$key]['prize_buckle_time'] = date('m-d', $value['prize_buckle_time']);
            }
        }
        $stat_data = [
            'rate_target' => $rate_target,//任务目标
            'total_rate' => $total_rate,//本月比例
            'total_prize' => $total_prize,//奖分
            'total_buckle' => $total_buckle,//扣分
            'total_people' => $total_people,//人次
        ];
        $data = [
            'stat_data' => $stat_data,
            'list' => $list,
            'page' => (int)$page,
            'count_page' => $count_page,
        ];
        return return_json(0, '获取成功', $data);
    }

    //奖扣任务人次任务详情
    public function people_task_info()
    {
        $uid = $this->user_id;
        $time = I('time', 0);
        $type = I('type', 1);
        if (empty($time)) {
            return return_json(1, '时间不能为空');
        }
        $start = strtotime($time . '-01');
        $end = strtotime('+1 month', $start)-1;
        $sys = M('com_prize_buckle_config_relation_users a')
            ->join('com_prize_buckle_config b', 'a.prize_buckle_id=b.id', 'left')
            ->where('a.user_id', $uid)
            ->field('b.*')
            ->find();
        //人次
        $where['c.first_check_user_id'] = $uid; //初审人
        $where['c.prize_buckle_time'] = ['between', [$start, $end]]; //奖扣时间范围
        $where['c.status'] = 2; //审核通过
        $where['a.is_cancellation'] = 0; //未作废
        $res_people = M('com_integral_event_relation_users a')
            ->join('com_integral_prize_buckle_relation_event b', 'b.id=a.event_id', 'left')
            ->join('com_integral_prize_buckle c', 'c.id=b.prize_buckle_id', 'left')
            ->join('users d', 'd.id=a.user_id', 'left')
            ->join('com_event e', 'e.id=b.event_id', 'left')
            ->where($where)
            ->order('c.prize_buckle_time desc')
            ->field('c.prize_buckle_time,d.name,e.name event_name,a.integral_b,c.people_sum')
            ->select();
        foreach ($res_people as $key => $value) {
            $res_people[$key]['day'] = date('d', $value['prize_buckle_time']);
            $res_people[$key]['prize_buckle_time'] = date('m-d', $value['prize_buckle_time']);
        }
        $data = [];
        $data_total = [];
        $sys['man_type'] = $type;
        if ($sys['man_type'] == 1) { //日任务
            $max = (int)date('d', $end);
            for ($i = 1; $i <= $max; $i++) {
                $data_day = [];
                $people_sum = 0;
                foreach ($res_people as $v) {
                    if ($v['day'] == $i) {
                        $data_day[] = $v;
                    }
                    $people_sum++;
                }
                $data[] = [
                    'time' => $i,
                    'people_sum' => $people_sum,
                    'data_day' => $data_day,
                ];
            }
            $data_total['type'] = 1;
        } elseif ($sys['man_type'] == 2) {//人次周任务
            //第一周
            $week_1_people_start = $start;
            $week_1_people_end = $start + 3600 * 24 * 7;
            $res_week_1_people = SendIntegralNew::statistic_prize_buckle($week_1_people_start,$week_1_people_end,$uid);
            $data_day = [];
            foreach ($res_people as $key => $value) {
                if ($value['day'] < 8) {
                    $data_day[] = $value;
                }
            }
            $data[] = [
                'time' => 1,
                'people_sum' => $res_week_1_people['people_sum'],
                'data_day' => $data_day,
            ];
            //第二周
            $week_2_people_start = $week_1_people_end;
            $week_2_people_end = $week_1_people_end + 3600 * 24 * 7;
            $res_week_2_people = SendIntegralNew::statistic_prize_buckle($week_2_people_start,$week_2_people_end,$uid);
            $data_day = [];
            foreach ($res_people as $key => $value) {
                if ($value['day'] >= 8 && $value['day'] <= 14) {
                    $data_day[] = $value;
                }
            }
            $data[] = [
                'time' => 2,
                'people_sum' => $res_week_2_people['people_sum'],
                'data_day' => $data_day,
            ];
            //第三周
            $week_3_people_start = $week_2_people_end;
            $week_3_people_end = $week_2_people_end + 3600 * 24 * 7;
            $res_week_3_people = SendIntegralNew::statistic_prize_buckle($week_3_people_start,$week_3_people_end,$uid);
            $data_day = [];
            foreach ($res_people as $key => $value) {
                if ($value['day'] >= 15 && $value['day'] <= 21) {
                    $data_day[] = $value;
                }
            }
            $data[] = [
                'time' => 3,
                'people_sum' => $res_week_3_people['people_sum'],
                'data_day' => $data_day,
            ];
            //第四周
            $week_4_people_start = $week_3_people_end;
            $week_4_people_end = $end;
            $res_week_4_people = SendIntegralNew::statistic_prize_buckle($week_4_people_start,$week_4_people_end,$uid);
            $data_day = [];
            foreach ($res_people as $key => $value) {
                if ($value['day'] > 21) {
                    $data_day[] = $value;
                }
            }
            $data[] = [
                'time' => 4,
                'people_sum' => $res_week_4_people['people_sum'],
                'data_day' => $data_day,
            ];
            $data_total['type'] = 2;
        } else {//人次月任务
            //月人次
//            $where_month_4_people['first_check_user_id'] = $uid; //初审人
//            $where_month_4_people['prize_buckle_time'] = ['between', [$start, $end]]; //奖扣时间范围
//            $where_month_4_people['status'] = 2; //审核通过
//            $res_month_people = M('com_integral_prize_buckle')
//                ->where($where_month_4_people)
//                ->field('COALESCE(sum(people_sum),0) people_sum,COALESCE(sum(integral_b_add),0) integral_b_add,COALESCE(sum(integral_b_del),0) integral_b_del')
//                ->find();
            $res_month_people = SendIntegralNew::statistic_prize_buckle($start,$end,$uid);
            $data = $res_people;
            $data_total = [
                'total_prize' => $res_month_people['integral_b_add'],
                'total_buckle' => $res_month_people['integral_b_del'],
                'total_people' => $res_month_people['people_sum'],
                'type' => 3
            ];
        }
        $data_total['people_target'] = $sys['man_num'];
        $data_a = [
            'list' => $data,
            'data_total' => $data_total
        ];
        return return_json(0, '获取成功', $data_a);

    }

    //请假申请
    public function my_leave()
    {
        $uid = $this->user_id;
        $page = I('page', 1);
        $where['a.user_id'] = $uid;
        $res = M('com_leave a')
            ->join('users b', 'b.id=a.user_id', 'left')
            ->join('com_department c', 'c.id=b.department_id', 'left')
            ->field('a.id,a.reason,a.start_time,a.create_time
            ,a.type,a.day,a.hour,a.deduct_marks,a.fixed_deduct,a.status
            ,b.name user_name,c.name department_name')
            ->where($where)
            ->order('a.create_time desc')
            ->paginate(11, false, page_param());
        $count = M('com_leave a')
            ->join('users b', 'b.id=a.user_id', 'left')
            ->join('com_department c', 'c.id=b.department_id', 'left')
            ->where($where)
            ->count();
        $count_page = ceil($count / 11);
        $list = $res->items();
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                $list[$key]['start_time'] = date('Y-m-d', $value['start_time']);
                $list[$key]['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
            }
        }
        $data = [
            'list' => $list,
            'page' => (int)$page,
            'count_page' => $count_page,
        ];
        return return_json(0, '获取成功', $data);
    }

    //请假详情
    public function leave_info()
    {
        $id = I('id', 0);
        if (empty($id)) {
            return return_json(1, '请假id不能为空');
        }
        $where['a.id'] = $id;
        $res = M('com_leave a')
            ->join('users b', 'b.id=a.user_id', 'left')
            ->join('users d', 'd.id=a.first_check_user_id', 'left')
            ->join('users f', 'f.id=a.last_check_user_id', 'left')
            ->join('com_department c', 'c.id=b.department_id', 'left')
            ->field('a.reason,a.start_time,a.create_time,a.reject_type,a.check_status
            ,a.first_check_desc,a.last_check_desc,a.first_check_time,a.last_check_time
            ,a.type,a.day,a.hour,a.deduct_marks,a.fixed_deduct,a.status,a.img
            ,b.name user_name,c.name department_name,d.name first_name,f.name last_name,a.first_check_user_id,a.last_check_user_id,a.user_id record_user_id')
            ->where($where)
            ->find();
        $res['start_time'] = date('Y-m-d', $res['start_time']);
        if (!empty($res['first_check_time'])) {
            $res['first_check_time'] = date('Y-m-d H:i:s', $res['first_check_time']);
        }
        if (!empty($res['last_check_time'])) {
            $res['last_check_time'] = date('Y-m-d H:i:s', $res['last_check_time']);
        }
        if (!empty($res['create_time'])) {
            $res['create_time'] = date('Y-m-d H:i:s', $res['create_time']);
        }
        if (!empty($res['img'])) {
            $res['img'] = explode(',', $res['img']);
//            foreach ($res['img'] as $key => $value) {
//                $res['img'][$key] = getImageUrl($value);
//            }
        } else {
            $res['img'] = [];
        }
        return return_json(0, '获取成功', $res);
    }

    //请假申请-获取参数
    public function get_leave_parameter()
    {
        $uid = $this->user_id;
        $com_id = $this->com_id;
        //查询用户固定扣分值
        $res = M('com_fixed_relation_users a')
            ->join('com_fixed_integral b', 'b.id=a.fixed_id', 'left')
            ->where('a.user_id', $uid)
            ->field('COALESCE(sum(b.integral),0) integral')
            ->find();
        if ($res['integral'] == 0) {
            $fixed_day = 0;
        } else {
            $max_day = (int)date('d', strtotime('+1 month -1 day', strtotime(date('Y-m-01', time()))));
            $fixed_day = round($res['integral'] / $max_day, 0);
        }
        //每天请假扣分
        $res_a = M('com_config')->where('com_id', $com_id)->find();
        if (empty($res_a)) {
            $leave_sick = 0;
            $leave_thing = 0;
            $leave_other = 0;
        } else {
            $leave_sick = $res_a['leave_sick'];
            $leave_thing = $res_a['leave_thing'];
            $leave_other = $res_a['leave_other'];
        }
        $data = [
            'fixed_day' => $fixed_day,//固定积分每天扣分
            'leave_sick' => $leave_sick,//病假每天扣分
            'leave_thing' => $leave_thing,//事假每天扣分
            'leave_other' => $leave_other,//其他每天扣分
        ];
        return return_json(0, '获取成功', $data);
    }

    //请假添加提交或拟稿编辑提交
    public function leave_add()
    {
        $uid = $this->user_id;
        $com_id = $this->com_id;
        $id = I('id', 0);//请假id
        $type = I('type', 1); //请假类型  1事假  2病假 3其他
        $reason = I('reason', '');//请假事由
        $img = I('img', '');//请假图片
        $start_time = I('start_time', '');//开始时间
        $day = I('day', 0);//请假天数
        $hour = I('hour', 0);//请假小时
        $deduct_marks = I('deduct_marks', 0);//请假扣分
        $fixed_deduct = I('fixed_deduct', 0);//固定扣分
        $first_check_user_id = I('first_check_user_id', '');//初审人
        $last_check_user_id = I('last_check_user_id', '');//终审人
        $first_check_desc = I('first_check_desc', '');//初审意见
        if (empty($reason)) {
            return return_json(1, '请假事由不能为空');
        }
        if (empty($start_time)) {
            return return_json(1, '开始时间不能为空');
        }
        if (empty($day) && empty($hour)) {
            return return_json(1, '请假天数和请假小时不能同时为空');
        }
        if (empty($first_check_user_id)) {
            return return_json(1, '初审人不能为空');
        }
        if (empty($last_check_user_id)) {
            return return_json(1, '终审人不能为空');
        }
        if ($first_check_user_id == $last_check_user_id) {
            return return_json(1, '初审人和终审人不能相同');
        }
        DB::startTrans();
        try {
            if (!empty($img)) {
                $img = json_decode(htmlspecialchars_decode($img), true);
                $img_a = [];
                foreach ($img as $key => $va) {
                    $img_a[] = $va['url'];
                }
                $img = implode(',', $img_a);
            } else {
                $img = '';
            }
            $status = 0;
            $first_check_time = null;
            if ($uid == $first_check_user_id) {//初审人是自己 直接初审通过
                $status = 1;
                $first_check_time = time();
            }
            $data = [
                'com_id' => $com_id,
                'user_id' => $uid,
                'type' => $type,
                'start_time' => strtotime($start_time),
                'day' => $day,
                'hour' => $hour,
                'deduct_marks' => $deduct_marks,
                'fixed_deduct' => $fixed_deduct,
                'first_check_user_id' => $first_check_user_id,
                'last_check_user_id' => $last_check_user_id,
                'reason' => $reason,
                'status' => $status,
                'img' => $img,
                'first_check_desc' => $first_check_desc,
                'first_check_time' => $first_check_time,
                'create_time' => time(),
            ];
            if (empty($id)) {
                //新增
                $id = M('com_leave')->insertGetId($data);
            } else {
                //编辑
                M('com_leave')->where('id', $id)->update($data);
            }
            //发送消息
            $data_message = [];
            //记录人
            $data_message[] = [
                'title' => '您有请假记录提交审核',
                'user_id' => $uid,
                'cate_type' => 7,//请假消息
                'type' => 4,//请假
                'relation_id' => $id
            ];
            if($status == 1){
                //终审人
                $data_message[] = [
                    'title' => '您有请假记录待审核(终审)',
                    'user_id' => $last_check_user_id,
                    'cate_type' => 1,//审核消息
                    'type' => 4,//请假
                    'relation_id' => $id
                ];
            }else {
                //初审人
                $data_message[] = [
                    'title' => '您有请假记录待审核(初审)',
                    'user_id' => $first_check_user_id,
                    'cate_type' => 1,//审核消息
                    'type' => 4,//请假
                    'relation_id' => $id
                ];
            }
            Message::send_message_list($data_message);
            DB::commit();
            return return_json(0);
        }catch (\Exception $exception){
            DB::rollback();
            return return_json(1,$exception->getMessage());
        }
    }

    //悬赏任务报名
    public function task_apply()
    {
        $uid = $this->user_id;
        $id = I('id', 0);
        $reason = I('reason', '');//报名理由
        if (empty($id)) {
            return return_json(1, 'id不能为空');
        }
        //查询报名状态
        $res = M('com_task_relation')
            ->where(['user_id' => $uid, 'task_id' => $id])
            ->find();
        $info = M('com_task')->where('id', $id)->find();
        if ($res['status'] == 1) {
            return return_json(1, '不能重复报名');
        }
        if ($info['apply_end_time'] < time()) {
            return return_json(1, '报名时间已截止');
        }
        DB::startTrans();
        try {
            //报名
            M('com_task_relation')->where(['user_id' => $uid, 'task_id' => $id])->update(['status' => 1,'reason'=>$reason]);
            //发放报名奖励
            $info['user_id'] = $uid;
            SendIntegralNew::add_record_integral($info, $info['apply_integral'], 0, 19, true);
            DB::commit();
            return return_json(0);
        } catch (\Exception $e) {
            DB::rollback();
            return return_json(1, $e->getMessage());
        }

    }

    //悬赏任务选择参与人
    public function task_select_take()
    {
        $id = I('id', 0);
        $user_ids = I('user_ids', '');
        if (empty($id)) {
            return return_json(1, 'id不能为空');
        }
        if (empty($user_ids)) {
            return return_json(1, '参与人不能为空');
        }
        $info = M('com_task')->where('id', $id)->find();
        if ($info['status'] != 2) {
            return return_json(1, '只有报名中状态才可以选择参与人');
        }
        DB::startTrans();
        try {
            $user_ids = json_decode(htmlspecialchars_decode($user_ids), true);
            $take_array = [];
            //添加参与人
            foreach ($user_ids as $key => $value) {
                $take_array[] = [
                    'com_id' => $this->com_id,
                    'task_id' => $id,
                    'user_id' => $value['user_id'],
                ];
            }
            M('com_task_relation_take')->insertAll($take_array);
            //修改状态
            M('com_task')->where('id', $id)->update(['status' => 3]);
            DB::commit();
            return return_json(0);
        } catch (\Exception $e) {
            DB::rollback();
            return return_json(1, $e->getMessage());
        }
    }

    //待我审核分类统计
    public function my_check_state()
    {
        $uid = $this->user_id;
        //奖扣任务
        $where_1_a = "(a.status = 0 and a.first_check_user_id = {$uid}) or (a.status = 1 and a.last_check_user_id = {$uid})";
        $prize_buckle_sum = M('com_integral_prize_buckle a')
            ->where($where_1_a)
            ->count();
        //任务
        $task_sum = M('com_task a')
            ->where($where_1_a)
            ->count();
        //公告
        $notice_sum = M('com_notice a')
            ->where($where_1_a)
            ->count();
        //请假
        $leave_sum = M('com_leave a')
            ->where($where_1_a)
            ->count();

        //任务大厅可报名数量
        $where_apply = [];
        $where_apply['a.type'] = 2;//悬赏任务
        $where_apply['a.status'] = 2;//报名中
        $where_apply['b.user_id'] = $uid;//报名用户
        $where_apply['b.status'] = 0;//未报名状态
        $task_apply_sum_1 = M('com_task a')
            ->join('com_task_relation b','b.task_id=a.id','right')
            ->where($where_apply)
            ->count();
        //任务大厅进行中的任务数量
        $where_apply = [];
        $where_apply['a.status'] = 3;//进行中
        $where_apply['a.principal_user_id'] = $uid;//我负责的
        $task_apply_sum_2 = M('com_task a')
            ->where($where_apply)
            ->count();
//        $task_apply_sum = $task_apply_sum_1+$task_apply_sum_2;
        //公告大厅有未阅读的公告数量
        $where_read = [];
        $where_read['a.status'] = 2;//公示中
        $where_read['b.user_id'] = $uid;//阅读用户
        $where_read['b.status'] = 0;//未阅读状态
        $notice_read_sum = M('com_notice a')
            ->join('com_notice_relation b','b.notice_id=a.id','right')
            ->where($where_read)
            ->count();
        $data = [
            'prize_buckle_sum' => $prize_buckle_sum,
            'task_sum' => $task_sum,
            'notice_sum' => $notice_sum,
            'leave_sum' => $leave_sum,
            'task_apply_sum' => $task_apply_sum_1,
            'task_principal_sum' => $task_apply_sum_2,
            'notice_read_sum' => $notice_read_sum,
        ];
        return return_json(0, '获取成功', $data);
    }
    //任务id获取参与人信息和事件信息
    public function submit_task(){
        $task_id = I('task_id',0);
        if(empty($task_id)){
            return return_json(1,'任务id不能为空');
        }
        $task_name= M('com_task')->where('id',$task_id)->field('name,status')->find();
        if(empty($task_name)){
            return return_json(1,'任务不存在');
        }
        if($task_name['status'] != 3 && $task_name['status'] != 2){
            return return_json(1,'任务状态不正确');
        }
        //获取事件
        //点击提交生产临时事件，如果有相同的名字则不生产
        $event_id = M('com_event')->where(['name'=>$task_name['name'],'type'=>2,'com_id'=>$this->com_id])->value('id');
        if(empty($event_id)){
            $eventData = [
                'name'=>$task_name['name'],
                'com_id'=>$this->com_id,
                'cate_id'=>3,
                'type'=>2,
                'create_time'=>time(),
            ];
            DB::startTrans();//开启事务
            try{
                $event_id = M('com_event')->insertGetId($eventData);
                DB::commit();//回滚
            }catch (\Exception $e){
                DB::rollback();//回滚
                return return_json(1,$e->getMessage());
            }
        }
        //获取参与人
        $event = M('com_event a')
            ->join('com_event_cate b', 'b.id=a.cate_id', 'left')
            ->join('com_event_cate c', 'c.id=b.pid', 'left')
            ->field('a.*,b.name cate_name,c.name p_cate_name')
            ->where('a.id', $event_id)
            ->select();
        $data = [];
        foreach ($event as $key=>$value) {
            //负责人
            $task_a = M('com_task a')
                ->join('users b', 'b.id=a.principal_user_id', 'left')
                ->field('b.name,b.id')
                ->where('a.id', $task_id)
                ->select();
            //参与人
            $task_b = M('com_task_relation_take a')
                ->join('users b', 'b.id=a.user_id', 'left')
                ->where('a.task_id', $task_id)
                ->field('b.name,b.id')
                ->select();
            $list = array_merge($task_a, $task_b);
            $data[$key]['event'] = $value;
            $data[$key]['users'] = $list;

        }
        return return_json(0,'成功',$data);
    }
    //获取全部员工接口
    public function get_all_users(){
        $where = [];
        $where['a.com_id'] = $this->com_id;
        $where['a.status'] = 1;
        $where['a.type'] = 1;
        $where['a.role_id'] = ['neq',''];
        $users = M('users a')
            ->join('com_department b','b.id=a.department_id','left')
            ->where($where)->field('a.id,a.name,b.name department_name')->select();
        return return_json(0,'获取成功',$users);
    }
    //获取服务协议接口
    public function get_server(){
        $server = M('admin_server')->where('id',1)->value('server_content');
        //$server = mb_substr($server,1,strlen($server)-2);
        return return_json(0,'成功',$server);
    }
    //请假数量
    public function get_leave_sum(){
        $user_id = $this->user_id;
        $count = M('com_leave')->where(['user_id'=>$user_id,'status'=>3])->count();
        return return_json(0,'成功',['count'=>$count]);
    }


}
